코딩 이야기/백준 풀이
백준 4963번: 섬의 개수 파이썬 코드(dfs)
우기 woogi
2021. 2. 14. 15:22
반응형
import sys
one = [-1,1,0,0,1,1,-1,-1]
two = [0,0,-1,1,1,-1,1,-1]
def dfs(a, b):
graph[a][b] = -1
for i in range(8):
if 0 <= a+one[i] < y and 0 <= b+two[i] < x:
if graph[a+one[i]][b+two[i]] == 1:
dfs(a+one[i], b+two[i])
return
while 1:
x, y = map(int, sys.stdin.readline().split())
if x == 0 and y == 0:
break
graph = []
count = 0
for _ in range(y):
line = list(map(int, sys.stdin.readline().split()))
graph.append(line)
for t in range(y):
for r in range(x):
if graph[t][r] == 1:
dfs(t, r)
count += 1
print(count)
전에 풀어둔 1010번 유기농 배추 문제와 비슷하여 코드를 조금 그대로 가져와서 풀었다.
Dfs로 풀었다.
반응형