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

Backtracking

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. 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

  1. Start at the maze's entry cell (typically top-left), marking it as part of the current path.
  2. If the current cell is the destination, record the successful path.
  3. 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.
  4. Mark the new cell as visited and recurse from there.
  5. 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).

Rat in a MazeO(2ⁿ²)
Find a path through 1-cells from the top-left corner to the bottom-right.
1
0
0
0
1
1
0
1
0
1
0
0
1
1
1
1
Step 1 / 10
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Visit (0,0) — try D, L, R, U
Python · Backtracking in Code
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

BestO(rows × cols)
AverageO(2^(rows×cols)) in dense mazes with many branches
WorstO(2^(rows×cols))
SpaceO(rows × cols) recursion depth and visited tracking

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.