- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 41 lines of Python from the credited upstream file the-maze-ii.py.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- No explicit loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import heapq5 6 7class Solution(object):8 def shortestDistance(self, maze, start, destination):9 """10 :type maze: List[List[int]]11 :type start: List[int]12 :type destination: List[int]13 :rtype: int14 """15 start, destination = tuple(start), tuple(destination)16 17 def neighbors(maze, node):18 for dir in [(-1, 0), (0, 1), (0, -1), (1, 0)]:19 cur_node, dist = list(node), 020 while 0 <= cur_node[0]+dir[0] < len(maze) and \21 0 <= cur_node[1]+dir[1] < len(maze[0]) and \22 not maze[cur_node[0]+dir[0]][cur_node[1]+dir[1]]:23 cur_node[0] += dir[0]24 cur_node[1] += dir[1]25 dist += 126 yield dist, tuple(cur_node)27 28 heap = [(0, start)]29 visited = set()30 while heap:31 dist, node = heapq.heappop(heap)32 if node in visited: continue33 if node == destination:34 return dist35 visited.add(node)36 for neighbor_dist, neighbor in neighbors(maze, node):37 heapq.heappush(heap, (dist+neighbor_dist, neighbor))38 39 return -140 41