Building on the concept of the original Maze problem, "The Maze II" adds a layer of optimization. Instead of just asking if a destination is reachable, it asks for the shortest distance the ball must travel to reach that destination. The movement rules remain the same: the ball rolls in one of four directions and only stops when it hits a wall or a boundary. The distance is the total number of empty cells the ball passes through across all its rolls.
This the Maze II interview question is frequently asked by Meta, Amazon, and Google. It elevates the challenge from simple reachability to a shortest-path problem in a weighted graph. Because each "edge" (a roll) can have a different length (number of cells traveled), a simple BFS is no longer sufficient unless you treat each step as a unit. However, the most efficient way to solve this is using Dijkstra's algorithm, which tests a candidate's ability to implement priority queues and manage distances in a more complex state space.
This problem utilizes the Shortest Path, Array, Matrix, Breadth-First Search, Graph, Depth-First Search, Heap (Priority Queue) interview pattern. You can model the maze as a graph where the stopping points are nodes and the rolls are edges with weights equal to the distance traveled. Dijkstra's algorithm is ideal here:
distance matrix initialized to infinity, with the start position set to 0.d for that roll.current_distance + d is smaller than the known distance to the new stopping point, update the distance matrix and push the new point to the heap.Start at (0,0), destination (0,3).
A common mistake in "The Maze II coding problem" is attempting to use a standard BFS. While BFS finds the fewest number of rolls, it does not necessarily find the shortest total distance because one roll might be very long while another is very short. Another error is not updating the distance to a stopping point if a shorter path is found later. Finally, candidates often struggle with the implementation details of a priority queue, such as forgetting to check if the distance extracted from the heap is already outdated.
Dijkstra's algorithm is one of the most important patterns for medium-to-hard interview questions. Practice implementing it until you can do it quickly and without bugs. Understand how it differs from BFS and when each is appropriate. For grid problems, always be mindful of how you calculate and store distances to avoid redundant work.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Minimum Path Cost in a Hidden Grid | Medium | Solve | |
| Find a Safe Walk Through a Grid | Medium | Solve | |
| The Maze III | Hard | Solve | |
| Minimum Obstacle Removal to Reach Corner | Hard | Solve | |
| Minimum Cost to Make at Least One Valid Path in a Grid | Hard | Solve |