
Problem:
What is the minimum number of movements for escape from the maze?
미로를 탈출하기 위해 최소한으로 얼마나 움직여야 하는가?
Conditions:
His coordinate is (1, 1) and the exit locates at (N, M). He can move one step at a time. During the movement, he has to avoid monsters, whose node is coded as 1.
from collections import deque
#Get input, N and M, separated by space.
n, m = map(int, input().split())
#Get 2 dimensional list of input.
graph = []
for i in range(n):
graph.append(list(map(int, input())))
#Define directions (Left, Right, Up, Down)
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 0]
#Define a function, bfs.
def bfs(x, y):
queue = deque()
queue.append((x, y))
#While-loop until queue is empty.
while queue:
x, y = queue.popleft()
#Location (nx, ny) distanced from current position.
for i in range(4):
nx = x + dx[i]
ny = y + dy[i}
#Ignore if the location is off-limit.
if nx < 0 or ny < 0 or nx >= n or ny >= m:
continue
#Ignore when he meets a wall.
if graph[nx][ny] == 0:
continue
#If visited the node, plus 1 distance
if graph[nx][ny] == 1:
graph[nx][ny] = graph[x][y] + 1
queue.append((nx, ny))
#Return the shortest distance to the most downright node.
return graph[n-1][m-1]
print(bfs(0,0))