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 = [startrow, startcol] and destination = [destinationrow, destinationcol], 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.

Input & Output

Example 1 — Basic Path
$ 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
💡 Note: Ball starts at (0,4), rolls left to (0,0), then down to (4,0), then right to (4,4). Total distance: 4 + 4 + 4 = 12 steps
Example 2 — No Path
$ 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
💡 Note: There is no way for the ball to stop at destination (3,2) because it's surrounded by walls and unreachable
Example 3 — Direct Path
$ 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: 6
💡 Note: Ball rolls up from (4,3) to (0,3), then left to (0,1). Distance: 4 + 2 = 6 steps

Constraints

  • m == maze.length
  • n == maze[i].length
  • 1 ≤ m, n ≤ 100
  • maze[i][j] is 0 or 1
  • start.length == 2
  • destination.length == 2
  • 0 ≤ startrow, destinationrow < m
  • 0 ≤ startcol, destinationcol < n
  • Both start and destination exist in an empty space

Visualization

Tap to expand
The Maze II: Ball Rolling to Find Shortest PathStart (0,4)Destination (2,4)← Roll left (4 steps)↓ Roll down (2 steps)Roll right (4 steps) →Total Distance: 4 + 2 + 4 = 10 stepsBall rolls until hitting wallThen chooses new direction
Understanding the Visualization
1
Input
Ball at start position, destination marked, walls block movement
2
Rolling
Ball rolls in direction until hitting wall, then can choose new direction
3
Shortest Path
Find minimum number of steps to reach destination
Key Takeaway
🎯 Key Insight: Model the problem as shortest path in a graph where nodes are stopping positions after rolling until hitting walls
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
142.0K Views
Medium Frequency
~25 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen