chyam

[백준] 2178번, python - 미로 탐색 본문

백준

[백준] 2178번, python - 미로 탐색

chyam_eun 2025. 9. 22. 15:16

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

from collections import deque

n, m = map(int,input().split())
miro = []
direct = [[1,0],[-1,0],[0,1],[0,-1]]

for i in range(n):
    miro.append(list(map(int,input())))

def bfs(x,y):
    queue = deque([(x,y,1)])
    visited = [[False] * m for _ in range(n)]
    visited[x][y] = True

    while queue:
        x, y, cnt = queue.popleft()
        if x == n-1 and y == m-1: # 끝에 도달 시 
            return cnt
        for dx, dy in direct:
            nx, ny = x + dx, y + dy
            if 0<= nx < n and 0 <= ny < m and not visited[nx][ny] and miro[nx][ny] == 1:
            # 지나갈수있는 길이고 아직 도달하지 않은 곳 
                visited[nx][ny] = True
                queue.append((nx,ny,cnt+1))

print(bfs(0, 0))