[백준] 2667* 단지번호 붙이기 (실버1)

AI·2025년 9월 11일

https://www.acmicpc.net/problem/2667

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;


/* 
1. 입력
   5≤N≤25
2. 자료
   배열, bfs
3. 풀이법
   1인거 끼리 묶어서 count값을 arraylist에 넣기
 */
public class Main {
    static int n;
    static boolean[][] vis;
    static int[] dx = {0,1,0,-1};
    static int[] dy = {1,0,-1,0};
    static char[][] map;
    static ArrayList<Integer> ans = new ArrayList<>();
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        n = Integer.parseInt(br.readLine());
        map= new char[n][n];
        vis = new boolean[n][n];
        for(int i=0;i<n;i++){
            String s = br.readLine();
            for(int j=0;j<n;j++){
                map[i][j] = s.charAt(j);
            }
        }

        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++){
                if(map[i][j]=='1' && !vis[i][j]){
                    ans.add(bfs(i,j));
                }
            }
        }

        Collections.sort(ans);
        System.out.println(ans.size());
        for(int a : ans)
            System.out.println(a);

    }

    static int bfs(int x, int y){
        int count = 0;
        ArrayDeque<int[]> q = new ArrayDeque<>();
        vis[x][y] = true;
        q.add(new int[]{x,y});

        while (!q.isEmpty()){
            var c = q.poll();
            count++;

            for(int d=0;d<4;d++){
                int nx = c[0]+dx[d];
                int ny = c[1]+dy[d];

                if(nx<0 || nx >= n || ny<0 || ny>=n || vis[nx][ny] || map[nx][ny] != '1') continue;
                vis[nx][ny] = true;
                q.add(new int[]{nx,ny});
            }
        }
        return count;
    }
}

===
dfs

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// dfs
public class Main {
    static char[][] map;
    static int N, cnt;
    static boolean[][] visit;
    
    // 상하좌우 순서
    static int[] dy = { -1, 1, 0, 0 };
    static int[] dx = {  0, 0,-1, 1 };
    
    // 각 단지의 값을 담는 list
    static List<Integer> list = new ArrayList<>();
    
    public static void main(String[] args) throws Exception{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        
        map = new char[N][];
        visit = new boolean[N][N];
        
        for (int i = 0; i < N; i++) {
            map[i] = br.readLine().toCharArray();
        }
        
        // 풀이
        // 2차원 배열 순회 탐색 visit 하지 않은 1 이 있으면 dfs 로 단지 탐색
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if( map[i][j] != '1' || visit[i][j] ) continue;
                
                // 새로운 단지 발견
                cnt = 0; // 초기화
                dfs(i, j);
                list.add(cnt); // 단지별 수
            }
        }
        
        // 오름차순으로 list 정렬
        Collections.sort(list);
        
        System.out.println(list.size());
        
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
    static void dfs(int y, int x) {
        // 방문 체크
        visit[y][x] = true;
        // 단수내 주택 수 증가
        cnt++;
        
        for (int d = 0; d < 4; d++) {
            int ny = y + dy[d];
            int nx = x + dx[d];
            
            // 새로운 좌표 (ny, nx) 대한 범위 체크, visit 체크
            if( ny < 0 || nx < 0 || ny >= N || nx >= N || map[ny][nx] != '1' || visit[ny][nx] ) continue;
            
            dfs(ny, nx);
        }
    }
}

bfs

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
// bfs
public class Main {
    static char[][] map;
    static int N, cnt;
    static boolean[][] visit;
    
    // 상하좌우 순서
    static int[] dy = { -1, 1, 0, 0 };
    static int[] dx = {  0, 0,-1, 1 };
    
    // 각 단지의 값을 담는 list
    static List<Integer> list = new ArrayList<>();
    static Queue<Node> queue = new ArrayDeque<>(); // bfs 큐
    
    public static void main(String[] args) throws Exception{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        
        map = new char[N][];
        visit = new boolean[N][N];
        
        for (int i = 0; i < N; i++) {
            map[i] = br.readLine().toCharArray();
        }
        
        // 풀이
        // 2차원 배열 순회 탐색 visit 하지 않은 1 이 있으면 dfs 로 단지 탐색
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if( map[i][j] != '1' || visit[i][j] ) continue;
                
                // 새로운 단지 발견
                cnt = 0; // 초기화
                bfs(i, j);
                list.add(cnt); // 단지별 수
            }
        }
        
        // 오름차순으로 list 정렬
        Collections.sort(list);
        
        System.out.println(list.size());
        
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }
    static void bfs(int y, int x) {
        
        queue.offer(new Node(y, x)); // 시작점을 queue 에 담고 시작
        visit[y][x] = true;
        cnt = 1;
        
        while( ! queue.isEmpty() ) {
            
            Node node = queue.poll();
            
            for (int d = 0; d < 4; d++) {
                int ny = node.y + dy[d];
                int nx = node.x + dx[d];
                
                // 새로운 좌표 (ny, nx) 대한 범위 체크, visit 체크
                if( ny < 0 || nx < 0 || ny >= N || nx >= N || map[ny][nx] != '1' || visit[ny][nx] ) continue;
                
                queue.offer(new Node(ny, nx));
                visit[ny][nx] = true;
                cnt++;
            }           
        }
    }
    
    static class Node{
        int y, x;
        Node(int y, int x){
            this.y = y; this.x = x;
        }
        @Override
        public String toString() {
            return "Node [y=" + y + ", x=" + x + "]";
        }
    }
}

0개의 댓글