Skip to content

Commit cdfaf8a

Browse files
committed
[DFS] baekjoon-2667
1 parent 84fa02f commit cdfaf8a

File tree

4 files changed

+82
-0
lines changed

4 files changed

+82
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
| 07 | | [Baekjoon-14501 퇴사](./src/DFS/P14501) | |
2727
| 08 | | [Baekjoon-10971 외판원 순회 2](./src/DFS/P10971) | |
2828
| 09 | | [Baekjoon-14500 테트로미노](./src/DFS/P14500) | |
29+
| 10 | | [Baekjoon-2667 단지번호붙이기](./src/DFS/P2667) | |
2930

3031
### BFS
3132

src/DFS/P2667/Main.java

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
}

src/DFS/P2667/README.md

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
## [baekjoon-2667] 단지번호붙이기
2+
3+
![image](https://user-images.githubusercontent.com/22045163/96833690-d1e65c00-147b-11eb-96dc-e0d257eac3ef.png)

src/DFS/P2667/input.txt

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
7
2+
0110100
3+
0110101
4+
1110101
5+
0000111
6+
0100000
7+
0111110
8+
0111000

0 commit comments

Comments
 (0)