Rat in a Maze
In an n×n grid of 0/1 cells, find all paths from (0,0) to (n−1,n−1) moving U/D/L/R through 1-cells, no cell reused.
Open on GeeksforGeeks ↗Intuition
Classic backtracking on a grid: at each cell try the four moves (in lexicographic order D,L,R,U so paths come out sorted), mark the cell visited so the path can't loop, and unmark when retreating.
Grid backtracking: mark the cell on entry so the path can't revisit itself, explore each direction, then unmark on the way out so other paths may use the cell. The unmark is what separates path enumeration from flood fill — a flood marks permanently because it only needs to visit once.
Approach
Try moves in D, L, R, U order
Emitting choices in alphabetical order yields the required sorted path strings for free.
Mark, recurse, unmark
Set visited before recursing, clear after — the grid doubles as the visited set.
Prune invalid moves
Out of bounds, walls (0), and visited cells are rejected before recursion, keeping the tree tight.
Solution & live demo
Common pitfalls
Not restoring the cell after exploring
maze[r][c] = 0
for ch, dr, dc in moves:
...maze[r][c] = 0
for ...:
...
maze[r][c] = 1 # unmarkCells stay blocked for every subsequent path, so only the first route is ever found. The mark exists to prevent revisiting within one path — once that path unwinds, the cell is available again.
Trying directions in an arbitrary order
moves = [("U",-1,0),("R",0,1),("D",1,0),("L",0,-1)]moves = [("D",1,0),("L",0,-1),("R",0,1),("U",-1,0)]GFG requires the paths in lexicographic order, and exploring in D-L-R-U order produces them sorted without a final sort. Any other order gives the same set of paths in the wrong sequence.
Not checking that the start or end is open
go(0, 0) return res
if not maze[0][0] or not maze[n-1][n-1]: return res
A blocked start would still be marked and explored from, and a blocked destination makes every search futile. Both guards are cheap and stop the recursion before it begins.
Edge cases
No path exists; return empty list.
Start is the destination — one path, the empty string.