GeeksforGeeks Medium

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, left L, right R or up U.
  • 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.

Constraints
  • 2 <= n <= 5
  • 0 <= maze[i][j] <= 1
backtrackingmatrix
Open on GeeksforGeeks ↗
02

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.
How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def ratInMaze(self, maze: list[list[int]]) -> list[str]:
▶3 n = len(maze)
▶4 res, path = [], []
▶5 moves = [(1, 0, "D"), (0, -1, "L"), (0, 1, "R"), (-1, 0, "U")]
▶6 
▶7 def walk(r, c):
▶8 if r == n - 1 and c == n - 1:
▶9 res.append("".join(path))
▶10 return
▶11 maze[r][c] = 0
▶12 for dr, dc, ch in moves:
▶13 nr, nc = r + dr, c + dc
▶14 if 0 <= nr < n and 0 <= nc < n and maze[nr][nc] == 1:
▶15 path.append(ch)
▶16 walk(nr, nc)
▶17 path.pop()
▶18 maze[r][c] = 1
▶19 
▶20 if maze[0][0] == 1 and maze[n - 1][n - 1] == 1:
▶21 walk(0, 0)
▶22 return res
startexitmovespaths foundboth corners are open: start the walk
atrow 0, col 0
movesnone
found0
Start at the top-left cell. Both corners hold 1, so a path may exist. The rat will try moves in the order down, left, right, up, which is alphabetical (D, L, R, U), so paths come out already sorted.
startexitmovespaths foundright is open: step R
atrow 0, col 0
movesnone
found0
Try right. Already ruled out here: down is a wall, left is off the grid. The cell right is inside the grid, holds 1 and is not on the current path, so the rat steps there and adds R to the moves. The cell it leaves stays green: blocked for every deeper step, so the path cannot loop back.
startexitmovesRpaths founddown is open: step D
atrow 0, col 1
movesR
found0
Try down. The cell down is inside the grid, holds 1 and is not on the current path, so the rat steps there and adds D to the moves. The cell it leaves stays green: blocked for every deeper step, so the path cannot loop back.
startexitmovesRDpaths founddown is open: step D
atrow 1, col 1
movesRD
found0
Try down. The cell down is inside the grid, holds 1 and is not on the current path, so the rat steps there and adds D to the moves. The cell it leaves stays green: blocked for every deeper step, so the path cannot loop back.
startexitmovesRDDpaths foundleft is open: step L
atrow 2, col 1
movesRDD
found0
Try left. Already ruled out here: down is off the grid. The cell left is inside the grid, holds 1 and is not on the current path, so the rat steps there and adds L to the moves. The cell it leaves stays green: blocked for every deeper step, so the path cannot loop back.
startexitmovesRDDLpaths foundno move left: reopen this cell
atrow 2, col 0
movesRDDL
found0
No moves left from row 2, col 0. Still to rule out: down is off the grid, left is off the grid, right is on the path, up is a wall. Unblock this cell before returning. This path leaves it for good, but a different path, reached through another branch, may still pass through it.
startexitmovesRDDpaths foundback at row 2, col 1: undo L
atrow 2, col 1
movesRDD
found0
Step back. Everything reachable after L from here has been explored, so remove L from the moves. The rat stands on row 2, col 1 again and tries its next direction.
startexitmovesRDDpaths foundright is open: step R
atrow 2, col 1
movesRDD
found0
Try right. The cell right is inside the grid, holds 1 and is not on the current path, so the rat steps there and adds R to the moves. The cell it leaves stays green: blocked for every deeper step, so the path cannot loop back.
startexitmovesRDDRpaths foundRDDRexit reached: record RDDR
atrow 2, col 2
movesRDDR
found1
At the exit. The moves so far, R D D R, are one complete path, so record it. Nothing lies beyond the exit, so return and let the search back up.
startexitmovesRDDpaths foundRDDRback at row 2, col 1: undo R
atrow 2, col 1
movesRDD
found1
Step back. Everything reachable after R from here has been explored, so remove R from the moves. The rat stands on row 2, col 1 again and tries its next direction.
startexitmovesRDDpaths foundRDDRno move left: reopen this cell
atrow 2, col 1
movesRDD
found1
No moves left from row 2, col 1. Still to rule out: up is on the path. Unblock this cell before returning. This path leaves it for good, but a different path, reached through another branch, may still pass through it.
startexitmovesRDpaths foundRDDRback at row 1, col 1: undo D
atrow 1, col 1
movesRD
found1
Step back. Everything reachable after D from here has been explored, so remove D from the moves. The rat stands on row 1, col 1 again and tries its next direction.
startexitmovesRDpaths foundRDDRno move left: reopen this cell
atrow 1, col 1
movesRD
found1
No moves left from row 1, col 1. Still to rule out: left is a wall, right is a wall, up is on the path. Unblock this cell before returning. This path leaves it for good, but a different path, reached through another branch, may still pass through it.
startexitmovesRpaths foundRDDRback at row 0, col 1: undo D
atrow 0, col 1
movesR
found1
Step back. Everything reachable after D from here has been explored, so remove D from the moves. The rat stands on row 0, col 1 again and tries its next direction.
startexitmovesRpaths foundRDDRright is open: step R
atrow 0, col 1
movesR
found1
Try right. Already ruled out here: left is on the path. The cell right is inside the grid, holds 1 and is not on the current path, so the rat steps there and adds R to the moves. The cell it leaves stays green: blocked for every deeper step, so the path cannot loop back.
startexitmovesRRpaths foundRDDRno move left: reopen this cell
atrow 0, col 2
movesRR
found1
No moves left from row 0, col 2. Still to rule out: down is a wall, left is on the path, right is off the grid, up is off the grid. Unblock this cell before returning. This path leaves it for good, but a different path, reached through another branch, may still pass through it.
startexitmovesRpaths foundRDDRback at row 0, col 1: undo R
atrow 0, col 1
movesR
found1
Step back. Everything reachable after R from here has been explored, so remove R from the moves. The rat stands on row 0, col 1 again and tries its next direction.
startexitmovesRpaths foundRDDRno move left: reopen this cell
atrow 0, col 1
movesR
found1
No moves left from row 0, col 1. Still to rule out: up is off the grid. Unblock this cell before returning. This path leaves it for good, but a different path, reached through another branch, may still pass through it.
startexitmovespaths foundRDDRback at row 0, col 0: undo R
atrow 0, col 0
movesnone
found1
Step back. Everything reachable after R from here has been explored, so remove R from the moves. The rat stands on row 0, col 0 again and tries its next direction.
startexitmovespaths foundRDDRno move left: reopen this cell
atrow 0, col 0
movesnone
found1
No moves left from row 0, col 0. Still to rule out: up is off the grid. Unblock this cell before returning. This path leaves it for good, but a different path, reached through another branch, may still pass through it.
startexitmovespaths foundRDDRanswer: RDDR
atrow 0, col 0
movesnone
found1
Return 1 path. Every cell was reopened on the way back, so the grid is back to how it started.
05

Common pitfalls

Never opening the cell again

✗ Wrong
maze[r][c] = 0
for dr, dc, ch in moves:
    ...
# no reset
✓ Right
maze[r][c] = 0
for dr, dc, ch in moves:
    ...
maze[r][c] = 1

The 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

✗ Wrong
moves = [(1, 0, "D"), (0, 1, "R"), (-1, 0, "U"), (0, -1, "L")]
✓ Right
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.

06

Edge cases

Start cell is 0

The corner check returns [] before any move; without it the rat would walk out of a wall.

Exit cell is 0

No path can end there, so the corner check returns [] at once instead of exploring the whole grid for nothing.

Exit reachable only by moving up or left

The search tries all four moves, so winding paths such as RRDDLLDDRRRR on a 5 × 5 grid are found too.

07

Complexity

Time
O(3^(n²))
Space
O(n²)
After the first move, each cell has at most 3 unvisited neighbours to try, and a path can be up to 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.
08

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.