-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS_ex2.py
More file actions
43 lines (35 loc) · 1.06 KB
/
DFS_ex2.py
File metadata and controls
43 lines (35 loc) · 1.06 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
'''
**Info**
GitHub name : yhlee0 (fresh2816@naver.com)
Subject : DFS_ex2
'''
#DFS로 특정노드 방문하고 연결된 모든 노드들도 방문
def dfs(x, y):
#주어진 범위를 벗어나는 경우에는 즉시 종료
if x <= -1 or x >= n or y <= -1 or y >= m:
return False
#현재 노드를 아직 방문하지 않았다면
if graph[x][y] == 0: #0==False
#해당 노드 방문 처리
graph[x][y] = 1 #1==True
#상, 하 좌, 우 위치들도 모두 재귀적으로 호출
dfs(x-1, y)
dfs(x, y-1)
dfs(x+1, y)
dfs(x, y+1)
return True
return False
#n, m을 공백을 기준으로 구분하여 입력받기
n, m = map(int, input().split())
#2차원 리스트의 맵 정보 입력받기
graph = []
for i in range(n):
graph.append(list(map(int, input())))
#모든 노드(위치)에 대하여 음료수 채우기
result = 0
for i in range(n):
for j in range(m):
#현재 위치에서 DFS 수행
if dfs(i, j) == True:
result += 1
print(result) #정답 출력