Algorithms · Visualized
Rat in a Maze
Backtracking
Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.
Given a maze grid with open and blocked cells, find a path for a rat to travel from the top-left to the bottom-right corner, moving only through open cells. Time: O(2^(rows×cols)) in dense mazes with many branches average, O(2^(rows×cols)) worst; space: O(rows × cols) recursion depth and visited tracking.
Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.
Rat in a Maze
BacktrackingGiven a maze grid with open and blocked cells, find a path for a rat to travel from the top-left to the bottom-right corner, moving only through open cells. Backtracking tries a direction, and if it later leads to a dead end, it undoes that step and tries a different direction.
How Rat in a Maze Works
- Start at the maze's entry cell (typically top-left), marking it as part of the current path.
- If the current cell is the destination, record the successful path.
- Otherwise, try moving in each allowed direction (commonly down and right, or all four directions) from the current cell, if that neighboring cell is open and not already visited in this path.
- Mark the new cell as visited and recurse from there.
- If a direction doesn't lead to the destination, backtrack: unmark the cell as visited and try the next direction.
Rat in a Maze Worked Example
Input: {maze: [[1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [1, 1, 1, 1]]}
Start (0,0). Move down to (1,0) [open]. Move down to (2,0)? Blocked (0) — try right to (1,1) [open] instead. Move down to (2,1) [open]. Move down to (3,1) [open]. Move right to (3,2) [open]. Move right to (3,3), the destination — path found: (0,0)→(1,0)→(1,1)→(2,1)→(3,1)→(3,2)→(3,3).
def rat_in_maze(maze):
n = len(maze)
path = []
def dfs(r, c):
if not (0 <= r < n and 0 <= c < n) or maze[r][c] != 1:
return False
path.append((r, c))
maze[r][c] = 2 # mark visited
if r == n - 1 and c == n - 1:
return True
for nr, nc in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:
if dfs(nr, nc):
return True
maze[r][c] = 1 # backtrack
path.pop()
return False
return path if dfs(0, 0) else []Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Rat in a Maze Time & Space Complexity
When to Use Rat in a Maze
- Pathfinding in robotics, games, and maze-solving applications.
- A foundational grid-backtracking pattern extended by algorithms like DFS/BFS pathfinding and Number of Islands.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.