-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2667.java
More file actions
79 lines (66 loc) · 1.96 KB
/
2667.java
File metadata and controls
79 lines (66 loc) · 1.96 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.*;
import java.util.*;
public class Main{
public static int[][] adj;
public static int N;
public static boolean[][] visited;
public static int cnt;
public static int aptCnt;
public static ArrayList<Integer> result;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
adj = new int[N][N];
visited = new boolean[N][N];
cnt = 0;
result = new ArrayList<>();
for (int i = 0;i<N;i++){
String str = br.readLine();
adj[i] = Arrays.stream(str.split("")).mapToInt(Integer::parseInt).toArray();
}
dfsAll();
System.out.println(cnt);
Collections.sort(result);
for(int j:result){
System.out.println(j);
}
}
public static boolean rangecheck(int x, int y){
if((x>=0&&x<N) &&(y>=0&&y<N)){
return true;
} else{
return false;
}
}
public static void dfs(int x,int y){
visited[x][y] = true;
if(rangecheck(x,y+1) && (!visited[x][y+1] && adj[x][y+1]==1)){
aptCnt++;
dfs(x,y+1);
}
if(rangecheck(x+1,y) && (!visited[x+1][y] && adj[x+1][y]==1)){
aptCnt++;
dfs(x+1,y);
}
if(rangecheck(x,y-1) &&(!visited[x][y-1] && adj[x][y-1]==1)){
aptCnt++;
dfs(x,y-1);
}
if(rangecheck(x-1,y) && (!visited[x-1][y] && adj[x-1][y]==1)){
aptCnt++;
dfs(x-1,y);
}
}
public static void dfsAll(){
for(int i=0;i<N;i++){
for(int j =0;j<N;j++) {
if (visited[i][j]==false&&adj[i][j] == 1) {
aptCnt = 1;
dfs(i, j);
cnt++;
result.add(aptCnt);
}
}
}
}
}