문제
코드
from collections import deque
import sys
input = sys.stdin.readline
dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]
def bfs(x: int, y: int):
queue = deque()
queue.append([x, y])
visited[x][y] = True
data[x][y] = 0
while queue:
x, y = queue.popleft()
for i in range(8):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < m and 0 <= ny < n and visited[nx][ny] == False and data[nx][ny] == 1:
visited[nx][ny] = True
queue.append([nx, ny])
data[nx][ny] = 0
if __name__ == '__main__':
m, n = map(int, input().split())
data = [list(map(int, input().split())) for _ in range(m)]
visited = [[False] * n for _ in range(m)]
cnt = 0
for x in range(m):
for y in range(n):
if data[x][y] == 1:
bfs(x, y)
cnt += 1
print(cnt)
결과
출처 & 깃허브
boj
github