알고리즘

백준 2178번 : 미로 탐색(python)

jenyy 2021. 1. 5. 21:10

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

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

from collections import deque
n,m = map(int,input().split())
data = [list(map(int,input())) for _ in range(n)]
dx = [-1,1,0,0]
dy = [0,0,-1,1]

def bfs(x,y):
    queue = deque()
    queue.append((x,y))
    while queue:
        x,y = queue.popleft()
        for i in range(4):
            nx,ny = x+dx[i],y+dy[i]
            if 0<=nx<n and 0<=ny<m and data[nx][ny]==1:
                data[nx][ny] = data[x][y]+1
                queue.append((nx,ny))
    return data[n-1][m-1]

print(bfs(0,0))