Skip to content
StackDecode
BacktrackingAnimated

Rat in a Maze

Explore moves, mark visited cells, and unmark on dead ends.

Time

O(4^(n²))

Extra space

O(n²)

Use it for

Path finding with backtracking.

How it works

  1. The rat starts at the top-left and must reach the bottom-right, moving only through open cells.
  2. From the current cell try the moves in the order Down, Left, Right, Up. Skip walls, the edge, and cells already on the current path.
  3. If a move works, step there and repeat. If none work, this cell is a dead end: step back and try another direction.
  4. The first time the exit is reached, the path is the answer.

Watch it run

Loading animation…