문제
https://www.acmicpc.net/problem/4963
Algorithm
Code
import sys
from collections import deque
input = sys.stdin.readline
dx = [0,0,1,-1,1,-1,1,-1]
dy = [1,-1,0,0,1,1,-1,-1]
def BFS(x,y):
queue = deque()
queue.append([x,y])
graph[y][x] = 0
while queue:
x,y = queue.popleft()
for i in range(8):
next_x = x + dx[i]
next_y = y + dy[i]
if 0 <= next_x < w and 0 <= next_y < h:
if graph[next_y][next_x] == 1:
queue.append([next_x,next_y])
graph[next_y][next_x] = 0
while(True):
graph = list()
w,h = map(int,input().split())
if(w == 0 and h == 0):
break
cnt = 0
for i in range(h):
graph.append(list(map(int,input().split())))
for i in range(h):
for j in range(w):
if graph[i][j] == 1:
BFS(j,i)
cnt += 1
print(cnt)