forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path10.py
34 lines (30 loc) ยท 1 KB
/
10.py
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
# N, M์ ๊ณต๋ฐฑ์ ๊ธฐ์ค์ผ๋ก ๊ตฌ๋ถํ์ฌ ์
๋ ฅ ๋ฐ๊ธฐ
n, m = map(int, input().split())
# 2์ฐจ์ ๋ฆฌ์คํธ์ ๋งต ์ ๋ณด ์
๋ ฅ ๋ฐ๊ธฐ
graph = []
for i in range(n):
graph.append(list(map(int, input())))
# DFS๋ก ํน์ ํ ๋
ธ๋๋ฅผ ๋ฐฉ๋ฌธํ ๋ค์ ์ฐ๊ฒฐ๋ ๋ชจ๋ ๋
ธ๋๋ค๋ ๋ฐฉ๋ฌธ
def dfs(x, y):
# ์ฃผ์ด์ง ๋ฒ์๋ฅผ ๋ฒ์ด๋๋ ๊ฒฝ์ฐ์๋ ์ฆ์ ์ข
๋ฃ
if x <= -1 or x >= n or y <= -1 or 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
# ๋ชจ๋ ๋
ธ๋(์์น)์ ๋ํ์ฌ ์๋ฃ์ ์ฑ์ฐ๊ธฐ
result = 0
for i in range(n):
for j in range(m):
# ํ์ฌ ์์น์์ DFS ์ํ
if dfs(i, j) == True:
result += 1
print(result) # ์ ๋ต ์ถ๋ ฅ