The Maze II Problem
Description
LeetCode Problem 505.
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. When the ball stops, it could choose the next direction.
Given the m x n maze, the ball's start position and the destination, where start = [start_row, start_col] and destination = [destination_row, destination_col], return the shortest distance for the ball to stop at the destination. If the ball cannot stop at destination, return -1.
The distance is the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included).
You may assume that the borders of the maze are all walls (see examples).
Example 1:

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.
The length of the path is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12.
Example 2:

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 = [3,2]
Output: -1
Explanation: There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there.
Example 3:
Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [4,3], destination = [0,1]
Output: -1
Constraints:
m == maze.lengthn == maze[i].length1 <= m, n <= 100maze[i][j]is0or1.start.length == 2destination.length == 20 <= start_row, destination_row < m0 <= start_col, destination_col < n- Both the ball and the destination exist in an empty space, and they will not be in the same position initially.
- The maze contains at least 2 empty spaces.
Solution
Approach: Dijkstra over Stopping Cells
As in The Maze, the ball can only stop next to a wall, so we search over stopping cells: from each one, rolling in one of four directions leads to the next stopping cell. The difference is that the moves now have different lengths. A roll that covers steps cells costs steps, so plain BFS (which counts moves) would not find the shortest distance. With positive edge weights, this is exactly Dijkstra's algorithm.
Keep dist[i][j], the shortest known distance to stop at (i, j), and a min-heap of (distance, row, col) entries, starting with (0, start):
- Pop the entry with the smallest distance. If it is larger than
distfor its cell, a better entry was already processed: skip it. - If the cell is the destination, its distance is final: return it.
- Otherwise, roll in each direction, counting the cells passed. If
d + stepsimproves the distance of the cell where the ball stops, update it and push it onto the heap.
If the heap empties without reaching the destination, the ball can never stop there, so return -1.
Why we can return at the first pop of the destination: Dijkstra pops cells in increasing order of distance, and every roll adds a non-negative length, so nothing popped later can lead to a shorter path. A roll straight into an adjacent wall has length 0 and lands on the same cell, which never improves anything, so it is harmless.
As before, the ball rolling over the destination does not count: only stopping cells enter dist.
Complexity: O(mn · max(m, n) + mn log(mn)) time: each stopping cell is expanded once with four rolls of up to max(m, n) steps, and each heap operation costs O(log(mn)). O(mn) space.
import heapq
class Solution:
def shortestDistance(self, maze: List[List[int]], start: List[int], destination: List[int]) -> int:
m, n = len(maze), len(maze[0])
inf = float("inf")
dist = [[inf] * n for _ in range(m)] # shortest distance to stop at each cell
dist[start[0]][start[1]] = 0
heap = [(0, start[0], start[1])]
while heap:
d, i, j = heapq.heappop(heap)
if d > dist[i][j]:
continue # an outdated entry
if [i, j] == destination:
return d
for a, b in ((-1, 0), (1, 0), (0, -1), (0, 1)):
# roll until the next cell is a wall or outside the maze
x, y, steps = i, j, 0
while 0 <= x + a < m and 0 <= y + b < n and maze[x + a][y + b] == 0:
x, y, steps = x + a, y + b, steps + 1
if d + steps < dist[x][y]:
dist[x][y] = d + steps
heapq.heappush(heap, (d + steps, x, y))
return -1