forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
the-maze-iii.py
42 lines (35 loc) · 1.35 KB
/
the-maze-iii.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
33
34
35
36
37
38
39
40
41
# Time: O(max(r, c) * wlogw)
# Space: O(w^2)
import heapq
class Solution(object):
def findShortestWay(self, maze, ball, hole):
"""
:type maze: List[List[int]]
:type ball: List[int]
:type hole: List[int]
:rtype: str
"""
ball, hole = tuple(ball), tuple(hole)
dirs = {'u' : (-1, 0), 'r' : (0, 1), 'l' : (0, -1), 'd': (1, 0)}
def neighbors(maze, node):
for dir, vec in dirs.iteritems():
cur_node, dist = list(node), 0
while 0 <= cur_node[0]+vec[0] < len(maze) and \
0 <= cur_node[1]+vec[1] < len(maze[0]) and \
not maze[cur_node[0]+vec[0]][cur_node[1]+vec[1]]:
cur_node[0] += vec[0]
cur_node[1] += vec[1]
dist += 1
if tuple(cur_node) == hole:
break
yield tuple(cur_node), dir, dist
heap = [(0, '', ball)]
visited = set()
while heap:
dist, path, node = heapq.heappop(heap)
if node in visited: continue
if node == hole: return path
visited.add(node)
for neighbor, dir, neighbor_dist in neighbors(maze, node):
heapq.heappush(heap, (dist+neighbor_dist, path+dir, neighbor))
return "impossible"