The Maze II - Solution & Explanation
Problem Statement
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 (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 <= startrow, destinationrow < m0 <= startcol, destinationcol < 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.
Approach Overview
Problem Overview: You are given a maze where a ball rolls in one direction until it hits a wall. From a start cell, find the minimum distance the ball must travel to stop exactly at the destination. Unlike typical grid problems, the ball does not stop at every cell—it only stops when it hits a wall, which makes pathfinding slightly different from standard BFS.
Approach 1: BFS with Distance Relaxation (O(mn * max(m,n)) time, O(mn) space)
A naive attempt is to treat the grid like a normal breadth-first search problem. From each stopping point, simulate rolling the ball in four directions until it hits a wall. Track the number of steps traveled during the roll and update the distance for the stopping cell if a shorter path is found. Because edges have different weights (the roll distance varies), the same cell might need to be revisited with a shorter distance. The algorithm maintains a distance matrix and pushes cells back into the queue whenever a shorter path is discovered.
Approach 2: Dijkstra with Priority Queue (O(mn log(mn)) time, O(mn) space)
The optimal solution models the maze as a weighted graph and runs Dijkstra’s algorithm. Each cell is a node, and rolling in a direction forms a weighted edge whose weight equals the number of steps traveled before hitting a wall. Use a min-heap (priority queue) to always process the cell with the smallest known distance. From the current cell, simulate rolling in four directions, compute the travel distance, and relax the distance if the new path is shorter. A distance matrix prevents unnecessary processing. This approach guarantees that once a node is popped from the heap with the minimum distance, its shortest path is finalized.
The grid structure naturally fits a graph shortest-path problem, while the rolling behavior defines the weighted edges. The key insight is that the ball travels multiple cells in one move, so every move has a variable cost rather than a uniform step.
Recommended for interviews: Dijkstra with a priority queue. Interviewers expect you to recognize that BFS alone does not work because the edge weights differ. Showing the BFS attempt demonstrates understanding of grid traversal, but identifying the weighted-graph nature and switching to Dijkstra shows strong algorithmic reasoning.
Solution
Code
Python
Java
C++
Go
TypeScript
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| BFS with Distance Relaxation | O(mn * max(m,n)) | O(mn) | Useful as a conceptual step when exploring the grid and simulating rolling movement |
| Dijkstra with Priority Queue | O(mn log(mn)) | O(mn) | Best for weighted shortest-path problems where movement cost varies |
Video Solution
LeetCode 505. The Maze II • Happy Coding • 5,195 views views
Watch 9 more video solutions →Frequently Asked Questions
Is The Maze II easy or hard?
The Maze II Python/Java solution
How to solve The Maze II in O(mn log mn)?
What is the best approach for The Maze II?
Is The Maze II asked at Google/Amazon/Meta?
What data structure is used in The Maze II?
What is the time complexity of The Maze II?
Ready to solve this problem?
Practice The Maze II with our built-in code editor and test cases.
Practice on FleetCode