문제풀이/DFS & BFS

[파이썬] [BFS] 백준 27211 도넛 행성

승무_ 2023. 1. 17. 09:03

문제

https://www.acmicpc.net/problem/27211

 

27211번: 도넛 행성

준겸이는 $N \times M$칸으로 이루어진 도넛 모양의 행성에 살고 있다. 준겸이가 살고 있는 행성에는 위 그림처럼 격자 모양으로 줄이 그어져 있다. 행성의 각 칸은 숲으로 막혀 있거나, 지나갈 수

www.acmicpc.net

코드

import sys
from collections import deque

queue=deque()
input=sys.stdin.readline

n, m = map(int, input().split())

graph = [list(map(int, input().split())) for _ in range(n)]
visited = [[False] * m for _ in range(n)]

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]


def bfs(i,j):
    visited[i][j] = True
    queue.append((i,j))

    while queue:
        r,c=queue.popleft()
        for k in range(4):
            if 0 <= r + dx[k] < n:
                nx = r + dx[k]
            elif r + dx[k] == n:
                nx = 0
            elif r + dx[k] == -1:
                nx = n - 1
            if 0 <= c + dy[k] < m:
                ny = c + dy[k]
            elif c + dy[k] == m:
                ny = 0
            elif c + dy[k] == -1:
                ny = m - 1
            if graph[nx][ny]==0 and visited[nx][ny]==False:
                visited[nx][ny] = True
                queue.append((nx,ny))


count = 0
for i in range(n):
    for j in range(m):
        if visited[i][j] == False and graph[i][j]==0:
            bfs(i,j)
            count+=1


print(count)