/
BAEKJOON 2667DFS
53 lines (50 loc) · 1.16 KB
/
BAEKJOON 2667DFS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.io.*;
import java.util.Arrays;
public class Main {
static int[][] arr, map;
static int[] dy = { 0, 1, 0, -1 };
static int[] dx = { -1, 0, 1, 0 };
static int [] c;
static int N, count;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
arr = new int[N][N];
map = new int[N][N];
c = new int[N*N];
for (int i = 0; i < N; i++) {
String str = br.readLine();
for (int j = 0; j < N; j++) {
arr[i][j] = str.charAt(j) - '0';
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (arr[i][j] == 1 && map[i][j] != 1) {
count++;
DFS(i, j);
}
}
}
System.out.println(count);
Arrays.sort(c);
for (int i = 0; i < c.length; i++) {
if(c[i]!=0)
System.out.println(c[i]);
}
}
static void DFS(int y, int x) {
map[y][x] = 1;
c[count]++;
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny < 0 || nx < 0 || ny >= N || nx >= N || arr[ny][nx] != 1 || map[ny][nx] == 1) {
ny = y - dy[i];
nx = x - dx[i];
continue;
}
DFS(ny,nx);
}
}
}