forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
32 lines (32 loc) · 1.15 KB
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution:
def findShortestWay(
self, maze: List[List[int]], ball: List[int], hole: List[int]
) -> str:
m, n = len(maze), len(maze[0])
r, c = ball
rh, ch = hole
q = deque([(r, c)])
dist = [[inf] * n for _ in range(m)]
dist[r][c] = 0
path = [[None] * n for _ in range(m)]
path[r][c] = ''
while q:
i, j = q.popleft()
for a, b, d in [(-1, 0, 'u'), (1, 0, 'd'), (0, -1, 'l'), (0, 1, 'r')]:
x, y, step = i, j, dist[i][j]
while (
0 <= x + a < m
and 0 <= y + b < n
and maze[x + a][y + b] == 0
and (x != rh or y != ch)
):
x, y = x + a, y + b
step += 1
if dist[x][y] > step or (
dist[x][y] == step and path[i][j] + d < path[x][y]
):
dist[x][y] = step
path[x][y] = path[i][j] + d
if x != rh or y != ch:
q.append((x, y))
return path[rh][ch] or 'impossible'