Rat in a Maze
Rat in a Maze is a GFG problem (Medium). You get an n × n grid maze of 0s and 1s. A rat starts at the top-left cell (0, 0) and wants to reach the bottom-right cell (n-1, n-1).
- It moves one cell at a time: down
D, leftL, rightRor upU. - It may only step on cells holding 1, and a single path may not visit a cell twice.
- Return every path as a string of move letters, in sorted (dictionary) order. If there is none, return an empty list.
The grid is at most 5 × 5, which is what makes trying every path affordable.
- 2 <= n <= 5
- 0 <= maze[i][j] <= 1
Intuition
Any path is a sequence of moves, so depth-first search with backtracking can try them all: step into an open neighbour, keep going until the exit or a dead end, then step back and try the next direction.
- No revisits: block the current cell while its branch is being explored, and open it again on the way back, so other paths may still use it.
- Sorted for free: try the moves in the order
D, L, R, U, which is alphabetical. Depth-first search then finishes paths in dictionary order, so no sort is needed at the end.
The rat in a maze problem asks you to list all routes, not find one or count the shortest, and the grid is tiny. Listing every route means exploring every branch, which is backtracking; breadth-first search only helps when one shortest route is wanted.
Approach
Before reading on: why must a cell be opened again after its branch is done, when the rat has already left it? And why does trying D before L before R before U give paths that are already sorted? Aim for no sorting step.
Check both corners first
If the start or the exit holds 0, return an empty list. The search would otherwise step from a blocked start, or never be able to finish.
Walk depth-first from the start
walk(r, c) stands on an open cell. If it is the exit, the current move string is one complete path, so record it and return; there is nothing to explore beyond the exit.
Block the cell you stand on
Set maze[r][c] = 0 before trying neighbours. Every deeper call then sees this cell as a wall, which is exactly the rule that a path never visits a cell twice, with no separate visited grid.
Try the four moves in D, L, R, U order
For each move, step only if the new cell is inside the grid and holds 1. Append the move letter, recurse, then remove the letter. Alphabetical move order means two paths that first differ at some step are finished in the order of that step's letter.
Open the cell on the way back
Set maze[r][c] = 1 after all four moves. The rat is leaving this cell for good on this path, but a different path reached through another branch may pass through it.
Code in Python, C++ and Java
Common pitfalls
Never opening the cell again
maze[r][c] = 0
for dr, dc, ch in moves:
...
# no resetmaze[r][c] = 0
for dr, dc, ch in moves:
...
maze[r][c] = 1The first branch that passes a cell leaves it blocked for every later branch. On a fully open 3 × 3 grid the answer has 12 paths; without the reset it returns only ["DDRR", "DDRURD"], because every cell the first branches pass through stays a wall.
Trying the moves in D, R, U, L order
moves = [(1, 0, "D"), (0, 1, "R"), (-1, 0, "U"), (0, -1, "L")]
moves = [(1, 0, "D"), (0, -1, "L"), (0, 1, "R"), (-1, 0, "U")]
The paths are all found, but not in sorted order: a path starting DR… would be listed before one starting DL…. Either try the moves alphabetically or sort the list before returning.
Edge cases
The corner check returns [] before any move; without it the rat would walk out of a wall.
No path can end there, so the corner check returns [] at once instead of exploring the whole grid for nothing.
The search tries all four moves, so winding paths such as RRDDLLDDRRRR on a 5 × 5 grid are found too.
Complexity
n² cells long, so 3^(n²) bounds the work. The real count is far smaller because walls and the no-revisit rule prune most branches, and n ≤ 5 keeps it tiny. Space is the recursion depth and the move string, both at most n², not counting the output.Rat in a Maze FAQ
Why not use a separate visited matrix?
It works the same way: mark the cell on entry, clear it on exit. Writing 0 into maze saves the extra n × n grid. If the caller needs the input unchanged, the search already restores every cell before it returns, so the grid ends up as it started.
What if the rat can only move down and right?
Then no cell can be revisited, so the blocking step disappears, and the number of paths can be counted with a small table: each open cell's count is the count above plus the count to the left. That counting version is Unique Paths II.