자기개발👨‍💻/코딩 알고리즘

[Python] 백준 2178 미로 탐색-dfs알고리즘-최단경로

천숭이 2023. 10. 18. 01:23
from collections import deque
import sys

input = sys.stdin.readline
n,m = map(int, input().split())
map = [list(map(int, input().strip())) for _ in range(n)]

dx = [1,0,-1,0]
dy = [0,1,0,-1]
def bfs(y,x):
    q=deque()
    q.append((y,x))
    cnt = 0
    while q:
        ey, ex = q.popleft()
        for k in range(4):
            xx = dx[k] + ex
            yy = dy[k] + ey
            if 0 <= yy < n and 0 <= xx < m and map[yy][xx] == 1:
                map[yy][xx] = map[ey][ex]+1
                q.append((yy,xx))

bfs(0,0)
print(map[-1][-1])