알고리즘 PS
[Python] 백준 #4963 섬의 개수
on_doing
2021. 1. 16. 19:02
728x90
4963번: 섬의 개수
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도
www.acmicpc.net
from collections import deque
import sys
def DFS(i, j):
que = deque()
if i < 0 or i >= h or j < 0 or j >= w:
return None
else:
if List[i][j] == 1:
que.append([i, j])
List[i][j] = 0
while que:
p = que.popleft()
xx = p[0]
yy = p[1]
for k in range(8):
x = dx[k]
y = dy[k]
if xx + x < 0 or xx + x >= h or yy + y < 0 or yy + y >= w:
continue
else:
if List[xx + x][yy + y] == 1:
que.append([xx + x, yy + y])
List[xx + x][yy + y] = 0
return True
else:
return None
while True:
w, h = map(int, sys.stdin.readline().rstrip().split())
if w == 0 and h == 0:
break
List = []
cnt = 0
dx = [-1, 1, 0, 0, -1, -1, 1, 1]
dy = [0, 0, -1, 1, -1, 1, -1, 1]
for i in range(h):
List.append(list(map(int, sys.stdin.readline().rstrip().split())))
for i in range(h):
for j in range(w):
k = DFS(i, j)
if k == None:
continue
else:
cnt += 1
print(cnt)
728x90