DSA Notes
Solve the Rat in a Maze problem using backtracking — navigate a grid, mark visited cells, backtrack on dead ends, and find all possible paths.
Problem Statement
Given an N×N binary grid where 1 represents an open cell and 0 represents a wall, a rat starts at the top-left corner (0,0) and must reach the bottom-right corner (N-1, N-1). The rat can move in four directions: Down (D), Right (R), Up (U), and Left (L). Find all possible paths (or determine if one exists), without visiting any cell more than once.
Intuition
Picture yourself in a physical maze. At each intersection, you have up to four corridors to try. You pick one and walk forward. If you hit a wall or a cell you have already visited, you turn around and try a different corridor from the last intersection. This is exactly what the algorithm does — recursively explore directions, marking cells as visited to avoid cycles, and unmarking them when backtracking.
Algorithm Steps
- Start at cell (0, 0). If it is blocked (value 0), no solution exists.
- Mark the current cell as visited.
- If the current cell is the destination (N-1, N-1), record the path.
- For each direction (D, L, R, U — often sorted alphabetically for lexicographic paths):
- Compute the next cell coordinates.
- If the next cell is within bounds, is open (value 1), and is not visited, recurse from that cell.
- After exploring all directions, unmark the current cell (backtrack) so it is available for other paths.
Dry Run on a 4×4 Grid
| Start (0,0) | mark visited |
| Move D | (1,0) → mark visited |
| Move D | (2,0) → mark visited |
| Move D | (3,0) = 0, WALL. Skip. |
| Move R | (2,1) → mark visited |
| Move D | (3,1) → mark visited |
| Move R | (3,2) → mark visited |
| Move R | (3,3) → DESTINATION! Path: "DDRDRR" |
| Move R | (2,2) = 0, WALL. Skip. |
| Move R | (1,1) → mark visited |
| Move D | (2,1) → mark visited |
| Move D | (3,1) → mark visited |
| Move R | (3,2) → mark visited |
| Move R | (3,3) → DESTINATION! Path: "DRDDRR" |
Both paths reach the destination. The algorithm finds all valid paths by exhaustive backtracking.
Python Implementation — Find All Paths
C++ Implementation
Single Path Variant (Return true/false)
Sometimes the problem only asks whether a path exists:
Key insight: If you only need *one* path, you do NOT need to unmark visited cells (no backtrack). If you need *all* paths, you must unmark after each recursive call returns.
Complexity Analysis
| Metric | Value | Explanation |
|---|---|---|
| Time (all paths) | O(4^(N²)) | Worst case: every cell reachable, 4 choices each |
| Time (one path) | O(N²) | Each cell visited at most once |
| Space | O(N²) | Visited matrix + recursion stack up to N² deep |
In practice, walls and the visited constraint prune heavily, making the actual runtime much smaller than the theoretical bound.
Common Variations
- Only Down and Right moves: Simpler — no cycles possible, no need for visited array. Each path has exactly (2N-2) moves.
- Weighted grid: Find the path with minimum cost — combine backtracking with pruning (if current cost exceeds known best, prune).
- Multiple rats or multiple destinations: Explore paths for each independently or find intersecting paths.
- Print the grid with path marked: Replace visited cells with a marker on the solution path.
Real-World Applications
- Robot navigation: Autonomous robots planning paths through physical spaces with obstacles
- Network routing: Finding paths through network topologies with failed nodes
- Game AI: NPC pathfinding in tile-based games (though BFS/A* is usually preferred for shortest path)
- PCB routing: Trace routing on circuit boards avoiding existing traces
Key Takeaways
The Rat in a Maze problem is a natural application of backtracking to grid traversal. The core pattern is: check bounds and constraints, mark visited, recurse in all valid directions, then unmark. Remember that unmarking is only necessary when you need *all* paths — for a single path, early termination without backtracking suffices.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Rat in a Maze.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, backtracking, rat, maze
Related Data Structures & Algorithms Topics