AcWing 844. 走迷宫
原题链接
中等
作者:
折木林森
,
2025-01-10 18:17:15
,
所有人可见
,
阅读 1
python代码
from collections import deque
n, m = map(int, input().split())
L = []
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
for i in range(n):
res = list(map(int, input().split()))
L.append(res)
def getNeighbors(s):
x = s[0]
y = s[1]
res = []
for i in range(4):
new_x = x + dx[i]
new_y = y + dy[i]
if 0 <= new_x < n and 0 <= new_y < m:
if L[new_x][new_y] == 0:
res.append((new_x, new_y))
return res
def bfs(L, start_x, start_y):
q = deque([(start_x, start_y)])
visit = set()
visit.add((start_x, start_y))
step = 0
while q:
sz = len(q)
for _ in range(sz):
cur = q.popleft()
if cur == (n - 1, m - 1):
return step
for to in getNeighbors(cur):
if to not in visit:
q.append(to)
visit.add(to)
step += 1
return -1
print(bfs(L, 0, 0))
注意newx和newy的范围!