백준 : 단지번호붙이기 – 2667번

import java.util.*;
public class Numbering {
    static int()() map;
    static boolean()() visited;
    static int() dx = {0, 0, 1, -1};
    static int() dy = {1, -1, 0, 0};
    static int N, count;
    static ArrayList<Integer> counts;

    public static void main(String() args) {
        Scanner sc = new Scanner(System.in);

        N = sc.nextInt();

        map = new int(N)(N);
        visited = new boolean(N)(N);
        counts = new ArrayList<Integer>();

        for (int i = 0; i < N; i++) {
            String row = sc.next();
            for (int j = 0; j < N; j++) {
                map(i)(j) = row.charAt(j) - '0';
            }
        }

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (map(i)(j) == 1 && !visited(i)(j)) { // 집이 있고 방문하지 않은 경우
                    count = 0; // 새로운 단지 시작
                    dfs(i, j); // dfs 탐색
                    counts.add(count); // 단지 내 집의 수 추가
                }
            }
        }

        Collections.sort(counts); // 오름차순 정렬

        System.out.println(counts.size()); // 총 단지 수 출력

        for (int i = 0; i < counts.size(); i++) {
            System.out.println(counts.get(i)); // 각 단지 내 집의 수 출력
        }
    }

    public static void dfs(int x, int y) {
        visited(x)(y) = true;
        count++;

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

            if (nx < 0 || ny < 0 || nx >= N || ny >= N) continue;
            if (map(nx)(ny) == 0 || visited(nx)(ny)) continue;

            dfs(nx, ny);
        }
    }
}