BOJ 2667 단지번호붙이기

이형욱·2025년 4월 28일
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/***
 * 시간 제한 1초, 메모리 제한 128MB
 * 5<=N<=25. -> N이 <=25이므로 N^3으로도 가능. n^2X4방 -> 25*25*4-> 2500?? 정도?
 * 아이디어: DFS 또는 BFS를 돌며 1을 0으로 바꿈. 완탐이 끝나고 나면 해당 영역의 개수를 리스트에 저장. -> 완탐이 개수를 return 하면 리스트에 저장하기 좋겠다.
 */
public class Main {
    // 동, 서, 남, 북
    static int[] dy = {0, 0, 1, -1};
    static int[] dx = {1, -1, 0, 0};
    static int N, res;
    static int[][] map;
    static List<Integer> list;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        // 1. 입력 값 받기.
        N = Integer.parseInt(br.readLine());
        map = new int[N][N];
        for(int i=0; i<N; i++){
            String str = br.readLine();
            for(int j=0; j<N; j++){
                map[i][j] = Integer.parseInt(str.charAt(j)+"");
            }
        }

        // 2. 자료형 준비
        res = 0; // 총 단지 수를 출력할 정답 변수 초기화.
        list = new ArrayList<>(); // 정답 저장 및 출력용 리스트.

        // 3. BFS 수행
        for(int i=0; i<N; i++){
            for(int j=0; j<N; j++){
                if(map[i][j]==1){
                    list.add(dfs(i,j));
                    res++;
                }
            }
        }

        // 4. 정답 출력.
        System.out.println(res);

        // 출력하기 전에 오름차순 정렬을 해야하네...
        Collections.sort(list);
        for(Integer num: list){
            System.out.println(num);
        }
    }

    static int dfs(int startY, int startX){
        int cnt = 1;

        Deque<int[]> queue = new ArrayDeque<>();
        map[startY][startX] = 0; // 방문 처리.
        queue.offer(new int[] {startY, startX});

        while(!queue.isEmpty()){
            int[] items = queue.poll();

            int y = items[0];
            int x = items[1];

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

                if(ny<0 || ny >=N || nx<0 || nx >= N) continue; // 범위 벗어나면.

                if(map[ny][nx] == 1){
                    map[ny][nx] = 0;
                    queue.offer(new int[] {ny, nx});
                    cnt++;
                }
            }
        }
        return cnt;
    }
}
profile
바나나는 하드디스크보다 따듯하다.

0개의 댓글