|
| 1 | +package DFS.P2667; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + |
| 8 | + static int N; |
| 9 | + static int[][] board; |
| 10 | + static boolean[][] visited; |
| 11 | + |
| 12 | + static int[] di = {-1, 0, 1, 0}; |
| 13 | + static int[] dj = {0, 1, 0, -1}; |
| 14 | + |
| 15 | + static ArrayList<Integer> list = new ArrayList<>(); |
| 16 | + static int count = 0; |
| 17 | + |
| 18 | + public static void main(String[] args) throws Exception { |
| 19 | + System.setIn(new FileInputStream("src/DFS/P2667/input.txt")); |
| 20 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 21 | + |
| 22 | + N = Integer.parseInt(br.readLine()); |
| 23 | + board = new int[N][N]; |
| 24 | + visited = new boolean[N][N]; |
| 25 | + |
| 26 | + for (int i = 0; i < N; i++) { |
| 27 | + String line = br.readLine(); |
| 28 | + for (int j = 0; j < N; j++) { |
| 29 | + board[i][j] = line.charAt(j) - '0'; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + for (int i = 0; i < N; i++) { |
| 34 | + for (int j = 0; j < N; j++) { |
| 35 | + if (!visited[i][j]) { |
| 36 | + dfs(i, j); |
| 37 | + if (count > 0) { |
| 38 | + list.add(count); |
| 39 | + count = 0; |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + Collections.sort(list); |
| 46 | + System.out.println(list.size()); |
| 47 | + for (int item: list) System.out.println(item); |
| 48 | + } |
| 49 | + |
| 50 | + static void dfs(int cur_i, int cur_j) { |
| 51 | + visited[cur_i][cur_j] = true; |
| 52 | + |
| 53 | + if (board[cur_i][cur_j] == 1) { |
| 54 | + count ++; |
| 55 | + |
| 56 | + for (int t = 0; t < 4; t++) { |
| 57 | + int to_i = cur_i + di[t]; |
| 58 | + int to_j = cur_j + dj[t]; |
| 59 | + |
| 60 | + if (isValidPath(to_i, to_j) && !visited[to_i][to_j]) { |
| 61 | + dfs(to_i, to_j); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + static boolean isValidPath(int i, int j) { |
| 68 | + return 0 <= i && i < N && 0 <= j && j < N; |
| 69 | + } |
| 70 | +} |
0 commit comments