AcWing 844. 走迷宫
原题链接
简单
作者:
皓首不倦
,
2020-08-09 01:32:35
,
所有人可见
,
阅读 480
from collections import deque
m, n = map(int, input().split())
grid = []
for i in range(m):
arr = list( map(int, input().split()) )
grid.append(arr)
visit = [[0] * n for _ in range(m)]
def bfs():
que = deque()
que.append((0, 0))
visit[0][0] = 1
step = 0
while len(que) > 0:
node_num = len(que)
for _ in range(node_num):
i, j = que.popleft()
if i == m-1 and j == n-1:
return step
for ii, jj in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:
if ii >= 0 and ii < m and jj >= 0 and jj < n and grid[ii][jj] == 0 and visit[ii][jj] == 0:
visit[ii][jj] = 1
que.append((ii, jj))
step += 1
return -1
print(bfs())