The Maze II — LeetCode 505 Python Solution
- Problem
- #505
- Pattern
- Heap / Priority Queue
- Reading time
- 4 min
- Source
- leetcode.com
The problem
There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall.
Example
- Input
- maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4]
- Output
- 12
- Explanation
- One possible way is : left -> down -> left -> down -> right -> down -> right.
Python solution
class Solution:
def shortestDistance(
self, maze: List[List[int]], start: List[int], destination: List[int]
) -> int:
m, n = len(maze), len(maze[0])
dirs = (-1, 0, 1, 0, -1)
si, sj = start
di, dj = destination
q = deque([(si, sj)])
dist = [[inf] * n for _ in range(m)]
dist[si][sj] = 0
while q:
i, j = q.popleft()
for a, b in pairwise(dirs):
x, y, k = i, j, dist[i][j]
while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0:
x, y, k = x + a, y + b, k + 1
if k < dist[x][y]:
dist[x][y] = k
q.append((x, y))
return -1 if dist[di][dj] == inf else dist[di][dj]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 505. The Maze II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 505. The Maze II?
- LeetCode 505. The Maze II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 505. The Maze II?
- The Python solution on this page runs in O(n log n).
- What is the space complexity of LeetCode 505. The Maze II?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 505. The Maze II cover?
- LeetCode 505. The Maze II is tagged Depth-First Search, Breadth-First Search, Graph, Array, Matrix, Shortest Path and Heap (Priority Queue) on LeetCode.
- Is LeetCode 505. The Maze II a premium problem?
- Yes. LeetCode 505. The Maze II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.