forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path10.java
57 lines (49 loc) ยท 1.69 KB
/
10.java
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
import java.util.*;
public class Main {
public static int n, m;
public static int[][] graph = new int[1000][1000];
// DFS๋ก ํน์ ๋
ธ๋๋ฅผ ๋ฐฉ๋ฌธํ๊ณ ์ฐ๊ฒฐ๋ ๋ชจ๋ ๋
ธ๋๋ค๋ ๋ฐฉ๋ฌธ
public static boolean dfs(int x, int y) {
// ์ฃผ์ด์ง ๋ฒ์๋ฅผ ๋ฒ์ด๋๋ ๊ฒฝ์ฐ์๋ ์ฆ์ ์ข
๋ฃ
if (x <= -1 || x >=n || y <= -1 || y >= m) {
return false;
}
// ํ์ฌ ๋
ธ๋๋ฅผ ์์ง ๋ฐฉ๋ฌธํ์ง ์์๋ค๋ฉด
if (graph[x][y] == 0) {
// ํด๋น ๋
ธ๋ ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
graph[x][y] = 1;
// ์, ํ, ์ข, ์ฐ์ ์์น๋ค๋ ๋ชจ๋ ์ฌ๊ท์ ์ผ๋ก ํธ์ถ
dfs(x - 1, y);
dfs(x, y - 1);
dfs(x + 1, y);
dfs(x, y + 1);
return true;
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// N, M์ ๊ณต๋ฐฑ์ ๊ธฐ์ค์ผ๋ก ๊ตฌ๋ถํ์ฌ ์
๋ ฅ ๋ฐ๊ธฐ
n = sc.nextInt();
m = sc.nextInt();
sc.nextLine(); // ๋ฒํผ ์ง์ฐ๊ธฐ
// 2์ฐจ์ ๋ฆฌ์คํธ์ ๋งต ์ ๋ณด ์
๋ ฅ ๋ฐ๊ธฐ
for (int i = 0; i < n; i++) {
String str = sc.nextLine();
for (int j = 0; j < m; j++) {
graph[i][j] = str.charAt(j) - '0';
}
}
// ๋ชจ๋ ๋
ธ๋(์์น)์ ๋ํ์ฌ ์๋ฃ์ ์ฑ์ฐ๊ธฐ
int result = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// ํ์ฌ ์์น์์ DFS ์ํ
if (dfs(i, j)) {
result += 1;
}
}
}
System.out.println(result); // ์ ๋ต ์ถ๋ ฅ
}
}