题目:
由空地(用 0 表示)和墙(用 1 表示)组成的迷宫 maze 中有一个球。球可以途经空地向 上、下、左、右 四个方向滚动,且在遇到墙壁前不会停止滚动。当球停下时,可以选择向下一个方向滚动。
给你一个大小为 m x n 的迷宫 maze ,以及球的初始位置 start 和目的地 destination ,其中 start = [startrow, startcol] 且 destination = [destinationrow, destinationcol] 。请你判断球能否在目的地停下:如果可以,返回 true ;否则,返回 false 。
你可以 假定迷宫的边缘都是墙壁(参考示例)。
解答:
class Solution:
def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool:
m=len(maze)
n=len(maze[0])
#四个方向
directions=[[-1,0],[1,0],[0,-1],[0,1]]
#distance[i][j]: 记录从起始位置start到 (i, j) 的最小步数
distance=[[float('inf')]*n for _ in range(m)]
#初始化
distance[start[0]][start[1]]=0
q=[(start[0],start[1])]
while q:
curx,cury=q.pop(0)
#选择某个方向滚动直到停下
for dx,dy in directions:
x,y=curx+dx,cury+dy
count=0
#一直沿着该方向前进,直到碰到墙壁停止
while x>=0 and x<m and y>=0 and y<n and (maze[x][y]==0):
x+=dx
y+=dy
count+=1
#从墙壁回退一步
x-=dx
y-=dy
tmp=distance[curx][cury]+count
#若tmp小于终点当前的最小步数,则对其进行更新
if tmp<distance[x][y]:
distance[x][y]=tmp
q.append((x,y))
x,y=destination
return True if distance[x][y]!=float('inf') else False