반응형
강의 : https://youtu.be/7C9RgOcvkvo
코드 :
# example - DFS problem
# 1. input
n, m = map(int, input().split())
graph = []
for i in range(n):
graph.append(list(map(int, input()))) # *no space*
def dfs(r,c):
# check out of boundary
if r<= -1 or r>n or c<=-1 or c>=m:
return False:
# check visited
if graph[r][c]==0:
graph[r][c] =1
# top, left, bottom, right
dfs(r-1, c)
dfs(r, c-1)
dfs(r+1, c)
dfs(r, c+1)
return True
return False
# 2. check node by DFS
result = 0
for i in range(n):
for j in range(m):
if dfs(i,j)==True:
result += 1
# 3. output result
print(result)
반응형