from collections import deque
def bfs(y, x):
q = deque()
q.append((y, x))
graph[y][x] = 0
while q:
y, x = q.popleft()
for dy, dx in d:
Y, X = y+dy, x+dx
if (0 <= Y < M) and (0 <= X < N) and graph[Y][X] == 1:
q.append((Y, X))
graph[Y][X] = 0
M, N = map(int, input().split())
graph = [list(map(int, input().split())) for _ in range(M)]
d = [(-1, -1), (-1, 1), (1, -1), (1, 1), (-1, 0), (1, 0), (0, -1), (0, 1)]
cnt = 0
for i in range(M):
for j in range(N):
if graph[i][j] == 1:
bfs(i, j)
cnt += 1
print(cnt)
대각선까지 살펴봐주면 된다.
'문제풀이 > 백준(Boj) 문제풀이' 카테고리의 다른 글
[백준][DFS/BFS] 11724. 연결 요소의 개수 (파이썬/Python) (0) | 2021.12.14 |
---|---|
[백준][BFS] 1697. 숨박꼭질(파이썬/Python) (0) | 2021.12.13 |
[백준][큐 & 덱] 1021. 회전하는 큐 (파이썬/Python) (0) | 2021.12.09 |
[백준][큐 & 덱] 5430. AC (파이썬/Python) (0) | 2021.12.07 |
[백준][큐 &덱] 10886. 덱 (파이썬/Python) (0) | 2021.12.07 |