The "The Maze" problem is a classic graph traversal challenge set in a 2D grid environment. You are given a maze represented by a matrix of 0s (empty spaces) and 1s (walls). You start at a specific coordinate with a ball that can roll in any of the four cardinal directions (north, south, east, west). However, there's a unique mechanic: once the ball starts rolling, it does not stop until it hits a wall or the boundary of the maze. Your goal is to determine if the ball can eventually reach a designated destination coordinate.
This the Maze interview question is a staple at companies like Uber, Square, and Meta because it tests a candidate's ability to adapt standard pathfinding algorithms (like BFS or DFS) to non-standard movement rules. While a typical maze problem allows you to stop at any cell, this version requires you to think in terms of "stopping points" rather than individual steps. It evaluates your recursion skills (for DFS) or queue management (for BFS) and your ability to handle complex boundary conditions.
The problem falls under the Array, Matrix, Breadth-First Search, Depth-First Search interview pattern. You can treat each "stopping point" as a node in a graph. From a given stopping point, you "roll" the ball in all four directions using a loop until it hits a wall. The cell right before the wall becomes a new potential stopping point. You can use BFS to find the shortest path of stopping points or DFS to simply check for reachability. To avoid infinite loops, you must maintain a visited set of the stopping points you've already explored.
Starting at (0,0) in a 5x5 maze where (0,4) is a wall and (4,0) is empty.
In "The Maze coding problem," a common error is marking every cell the ball passes through as visited. This is incorrect because the ball can pass through the same cell multiple times from different directions; only the stopping points need to be tracked to ensure the search terminates. Another mistake is incorrectly handling the "roll" logic, such as stopping the ball inside the wall rather than at the empty cell just before it.
When faced with grid-based movement problems, always clarify the stopping conditions. Is it a step-by-step move or a "slide until you hit something" move? Practice writing a helper function like roll(start_x, start_y, direction) to keep your main BFS/DFS logic clean and readable. This modular approach is highly appreciated by interviewers.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Shortest Bridge | Medium | Solve | |
| Pacific Atlantic Water Flow | Medium | Solve | |
| Minesweeper | Medium | Solve | |
| Find All Groups of Farmland | Medium | Solve | |
| Coloring A Border | Medium | Solve |