问题描述
使用洪水漫灌算法即可
import collections
class Solution:
def nearestExit(self, maze, entrance):
directions = [(-1,0),(1,0),(0,-1),(0,1)]
m = len(maze)
n = len(maze[0])
to_check = collections.deque([entrance])
maze[entrance[0]][entrance[1]]="+"
temp_q = collections.deque()
path = 0
success = 0
while to_check and not success:
path+=1
while to_check and not success:
x,y = to_check.popleft()
for dx,dy in directions:
nx = x+dx
ny = y+dy
if 0<=nx<m and 0<=ny<n and maze[nx][ny]==".":
if nx==0 or nx==m-1 or ny==0 or ny==n-1:
success=1
break
else:
maze[nx][ny]="+"
temp_q.append([nx,ny])
to_check = temp_q
temp_q = collections.deque()
if success:
return path
else:
return -1
maze = [["+",".","+","+","+","+","+"],["+",".","+",".",".",".","+"],["+",".","+",".","+",".","+"],["+",".",".",".","+",".","+"],["+","+","+","+","+","+","."]]
entrance = [0, 1]
print(Solution().nearestExit(maze,entrance))
运行结果:
参考这篇博客
学到了以下:
- dirs = [0, 1, 0, -1, 0],y是x的索引+1对应的值
- 第二层循环使用len,可以避免temp_q的使用
代码如下
directions = [0,-1,0,1,0]
m = len(maze)
n = len(maze[0])
to_check = collections.deque([entrance])
maze[entrance[0]][entrance[1]]="+"
path = 0
while to_check:
path+=1
for _ in range(len(to_check)):
x,y = to_check.popleft()
for j in range(4):
nx = x+directions[j]
ny = y+directions[j+1]
if 0<=nx<m and 0<=ny<n and maze[nx][ny]==".":
if nx==0 or nx==m-1 or ny==0 or ny==n-1:
return path
else:
maze[nx][ny]="+"
to_check.append([nx,ny])
return -1
运行结果