AlgoViz

Grid backtracking

medium 25 min

Grid backtracking is depth-first search on a 2D board where the visited mark belongs to the current path: mark a cell on the way in, explore its neighbours, unmark it on the way out so other paths can use it.

Video lesson · Chapter 1 of 10

The letter floor

0:00 / 6:49

Grid backtracking in 75 seconds

1:26Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Mark. Claim the cell for the current path: overwrite it with # or add it to a seen set

Understand it

Start here

Backtracking, now on a board

  • Recap: backtracking

    Choose, explore, unchoose over a tree of decisions, pruning dead branches early. Basics and 4-Queens live in Backtracking.

  • Recap: grid DFS

    A grid is an implicit graph: neighbours come from a direction array and a bounds check. Islands and flood fill live in Matrix DFS.

  • What is new here

    The visited mark is part of the choice: it must be undone. That one change turns flood fill into path enumeration, Word Search, N-Queens and Sudoku.

Grid backtracking is like walking a maze and dropping breadcrumbs behind you: you never step on your own crumbs, and when you back out of a dead end you pick them up, so the next route you try can walk there. This page goes past the basics: pruning Word Search, listing every path through a maze, counting paths versus listing them, N-Queens with O(1)O(1) checks, and a Sudoku solver.

The core move

Mark, explore, restore

Every grid backtracking call does the same three things. Mark the cell so the current path cannot step on it twice. Explore the four neighbours from a direction array: down (1,0)(1, 0), up (−1,0)(-1, 0), right (0,1)(0, 1), left (0,−1)(0, -1). Restore the cell before returning.

One call of a grid backtracking search

The only difference from Matrix DFS is the restore step: flood fill leaves cells marked forever.
Python
DIRS = ((1, 0), (-1, 0), (0, 1), (0, -1))   # down, up, right, leftdef search(grid, r, c, depth, ok, goal):    if goal(r, c, depth):        return True    if not (0 <= r < len(grid) and 0 <= c < len(grid[0])) or not ok(grid[r][c], depth):        return False    saved, grid[r][c] = grid[r][c], "#"           # mark    found = any(search(grid, r + dr, c + dc, depth + 1, ok, goal) for dr, dc in DIRS)    grid[r][c] = saved                            # restore    return foundg = [list("CAT"), list("XXO")]word = "CATO"print(search(g, 0, 0, 0, lambda ch, d: d < len(word) and ch == word[d], lambda r, c, d: d == len(word)))  # Trueprint(g)   # unchanged: [['C', 'A', 'T'], ['X', 'X', 'O']]
The template. ok decides if a cell may extend the path; the mark and restore bracket the recursion.
Edit and run it in your browser

Visited marks

Unmark or keep marked?

Both flood fill and backtracking mark cells, but they ask different questions. Flood fill asks "which cells can I reach?": once a cell is reached, it is reached, so it stays marked and every cell is processed once. Backtracking asks "which paths exist?": a cell can sit on many different paths, so it is only off-limits while it is on the current one.

Unmark on the way back (backtracking)

  • Word Search: the same letter cell can belong to a path from another start.
  • Listing or counting every path through a maze.
  • Longest simple path, or a path that visits every cell once.
  • Cost: exponential, since each cell is visited once per path.

Keep marked forever (plain DFS)

  • Number of islands, flood fill, connected regions.
  • Is the exit reachable at all? (a yes / no question).
  • Any question about cells, not about paths.
  • Cost: O(R⋅C)O(R \cdot C), since each cell is visited once in total.
How to markUndoWhen to use
Overwrite in place: board[r][c] = "#"board[r][c] = savedMutable grid, no extra memory; Word Search
seen set of (r, c)seen.discard((r, c))Grid must stay untouched, or cells hold numbers
Boolean matrix used[r][c]used[r][c] = FalseMany lookups, a bit faster than a set
Bitmask over cellsmask ^ (1 << (r * C + c))Tiny grids where the mask can be memoised
Overwriting with # works for Word Search because # never equals a letter, so the letter check also rejects marked cells.

Pattern 1

Word search with pruning

The basic search is covered in Backtracking. Two prunes run before any search and often decide the answer on their own. First, count letters: if the word needs three Cs and the board has two, return False at once. Second, if the first letter of the word is more common on the board than the last, search for the reversed word: fewer starting cells, fewer doomed searches.

Word Search with both prunes

On the board ABCE / SFCS / ADEE, ABCCED has two possible starts (two As) but its reverse DECCBA has one (one D).

Cost of one Word Search

T=O(R⋅C⏟starts⋅4⋅3L−1⏟paths of length L)=O(R⋅C⋅3L),S=O(L)T = O\big(\underbrace{R \cdot C}_{\text{starts}} \cdot \underbrace{4 \cdot 3^{L-1}}_{\text{paths of length } L}\big) = O\big(R \cdot C \cdot 3^{L}\big), \qquad S = O(L)
The first step has 4 directions; every later step at most 3, because the cell you came from is marked. The old bound O(R⋅C⋅4L)O(R \cdot C \cdot 4^L) is correct but loose.
Python
from collections import Counterdef exist(board, word):    rows, cols = len(board), len(board[0])    have = Counter(ch for row in board for ch in row)    if any(have[ch] < k for ch, k in Counter(word).items()):        return False                       # prune: not enough letters    if have[word[0]] > have[word[-1]]:        word = word[::-1]                  # start from the rarer end    def dfs(r, c, i):        if i == len(word):            return True        if not (0 <= r < rows and 0 <= c < cols) or board[r][c] != word[i]:            return False        board[r][c] = "#"                  # mark        found = any(dfs(r + dr, c + dc, i + 1) for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)))        board[r][c] = word[i]              # restore        return found    return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))b = [list("ABCE"), list("SFCS"), list("ADEE")]print([exist(b, w) for w in ["ABCCED", "SEE", "ABCB", "ABCCC"]])   # [True, True, False, False]print(exist([list("CODE"), list("ABCD"), list("EFGH")], "CODE"))   # True
Word Search with letter-count pruning and rarer-end-first.
Edit and run it in your browser

Worked example

ABCCED, SEE and CODE, traced

Board ABCE / SFCS / ADEE, directions tried down, up, right, left. Watch the marks go down and come back up.

WordPruneWhat the search doesResult
ABCCCneeds 3 C, board has 2No search at all.False
ABCCEDA ×2, D ×1: search DECCBAStart at the only D (2, 1). E right, C up, C up, B left, A left. Six cells marked, then all six restored.True
SEES ×2, E ×3: keepS at (1, 0) has no E next to it: mark, fail, unmark. S at (1, 3): E below, then the up move hits its own #, so E to the left.True
ABCBnone appliesA, B, C match; the only B next to C is already marked on this path.False
CODE on CODE / ABCD / EFGHC ×2, E ×2: keepFrom (0, 0): down A fails, up is off the grid, right O, right D, right E.True
The final path for ABCCED is (0, 0) → (0, 1) → (0, 2) → (1, 2) → (2, 2) → (2, 1), found backwards from D.

Pattern 2

Rat in a maze: list every path

A rat starts at the top-left of an n×nn \times n maze of 1s (open) and 0s (walls) and wants the bottom-right. List every path as a string of moves. Trying moves in the order D, L, R, U makes the output come out already sorted.

Python
def rat_paths(maze):    n = len(maze)    paths = []    moves = ((1, 0, "D"), (0, -1, "L"), (0, 1, "R"), (-1, 0, "U"))    def go(r, c, path):        if (r, c) == (n - 1, n - 1):            paths.append("".join(path))            return        maze[r][c] = 0                     # mark        for dr, dc, ch in moves:            nr, nc = r + dr, c + dc            if 0 <= nr < n and 0 <= nc < n and maze[nr][nc] == 1:                path.append(ch)                go(nr, nc, path)                path.pop()        maze[r][c] = 1                     # restore    if maze[0][0] == 1 and maze[n - 1][n - 1] == 1:        go(0, 0, [])    return pathsm = [[1, 0, 0, 0],     [1, 1, 0, 1],     [1, 1, 0, 0],     [0, 1, 1, 1]]print(rat_paths(m))   # ['DDRDRR', 'DRDDRR']
Mark by setting the cell to 0, restore it to 1. The maze ends unchanged.
Edit and run it in your browser
MomentPath so farWhat happens
1DDRDRRDown, down, wall below so right, down, right, right: the exit. List it.
2DDR + UBack up to (2, 1), unmarking (3, 2) and (3, 1). Up to (1, 1): every neighbour is marked or a wall. Dead end, unmark.
3D + RUnwind to (1, 0) and go right. (1, 1) is free again because it was unmarked.
4DRDDRRDown, down, right, right: the exit again, through (2, 1), (3, 1), (3, 2), cells the first path also used.
Had the first path left its cells marked, the second path would never be found. Unmarking is what makes all paths visible.

Pattern 3

Counting paths versus listing them

To count instead of list, return 1 at the goal and add up what the neighbours return. That saves memory but not time: the search tree is the same. The real question is whether the count from a cell depends on the path so far. With right and down moves only it does not, so a table answers in O(R⋅C)O(R \cdot C), as in Unique Paths. With four directions it does, because the cells already used block some futures.

Right and down only: a recurrence

ways(r,c)=ways(r−1,c)+ways(r,c−1),ways(R−1,C−1)=(R+C−2R−1)\text{ways}(r, c) = \text{ways}(r-1, c) + \text{ways}(r, c-1), \qquad \text{ways}(R-1, C-1) = \binom{R + C - 2}{R - 1}
For a 4×44 \times 4 grid: (63)=20\binom{6}{3} = 20. Each cell is computed once.
GridRight / down paths (DP)4-direction simple paths (backtracking)
3 × 3612
4 × 420184
5 × 5708,512
6 × 62521,262,816
Four-direction paths that never revisit a cell are self-avoiding walks. They have no closed formula, and the count grows so fast that only small grids can be enumerated.

Count, list, or just check?

Backtracking is the last resort, and the right one, when the answer depends on the whole path.

Pattern 4

N-Queens with column and diagonal sets

Put one queen per row, so row rr only chooses a column cc. Scanning the board to see if (r,c)(r, c) is attacked costs O(N)O(N). Three sets make it O(1)O(1): used columns, used values of r−cr - c, used values of r+cr + c.

Why two diagonal sets are enough

same down-right diagonal  ⟺  r1−c1=r2−c2,same down-left diagonal  ⟺  r1+c1=r2+c2\text{same down-right diagonal} \iff r_1 - c_1 = r_2 - c_2, \qquad \text{same down-left diagonal} \iff r_1 + c_1 = r_2 + c_2
Moving one step down-right adds 1 to both rr and cc, so r−cr - c is unchanged; moving down-left adds 1 to rr and subtracts 1 from cc, so r+cr + c is unchanged. On an N×NN \times N board there are 2N−12N - 1 diagonals of each kind.

The O(1) safety check

Three lookups replace a scan of the board. For speed, the three sets can become three integers used as bitmasks.
Python
def total_n_queens(n):    cols, diag, anti = set(), set(), set()    def place(r):        if r == n:            return 1        count = 0        for c in range(n):            if c in cols or r - c in diag or r + c in anti:                continue            cols.add(c); diag.add(r - c); anti.add(r + c)            count += place(r + 1)            cols.remove(c); diag.remove(r - c); anti.remove(r + c)        return count    return place(0)print([total_n_queens(n) for n in range(1, 10)])   # [1, 0, 0, 2, 10, 4, 40, 92, 352]
Count N-Queens solutions with sets, then check the classic counts.
Edit and run it in your browser

Pattern 5

Sudoku solver: constraint checks

Fill each empty cell with a digit that is not already in its row, its column or its box. Keep a set of used digits for every row, column and box so each check is O(1)O(1). When a cell has no legal digit, undo the last choice and try its next digit. A 4 × 4 puzzle (digits 1 to 4, 2 × 2 boxes) shows every idea at phone size.

Which box is a cell in?

box(r,c)=⌊rb⌋⋅b+⌊cb⌋,b=n\text{box}(r, c) = \left\lfloor \frac{r}{b} \right\rfloor \cdot b + \left\lfloor \frac{c}{b} \right\rfloor, \qquad b = \sqrt{n}
For a 9×99 \times 9 board b=3b = 3 and the boxes are numbered 0 to 8 row by row. Writing ⌊r/3⌋+⌊c/3⌋\lfloor r/3 \rfloor + \lfloor c/3 \rfloor instead gives the same id to different boxes.

Sudoku solver

On the 4 × 4 puzzle in the visualizer, cell (2, 1) first tries 1, which leaves (2, 3) with no digit; undoing it and trying 3 solves the board.

Complexity

Bounds you should be able to state

All simple paths on an R × C grid

T=O(4⋅3R⋅C−1)⊆O(4R⋅C),S=O(R⋅C)T = O\big(4 \cdot 3^{R \cdot C - 1}\big) \subseteq O\big(4^{R \cdot C}\big), \qquad S = O(R \cdot C)
A path can be up to R⋅CR \cdot C cells long, with at most 3 new directions per step after the first. Space is the path and the recursion stack, which can be as deep as the grid is large.

N-Queens

T(N)≤N⋅(N−1)⋅(N−2)⋯1=O(N!),S=O(N)T(N) \le N \cdot (N-1) \cdot (N-2) \cdots 1 = O(N!), \qquad S = O(N)
Row 0 has NN columns to try; by row kk at least kk columns are used, so at most N−kN - k remain. Diagonal pruning makes the real count far smaller.
ProblemTimeSpace
Word Search, word of length LLO(R⋅C⋅3L)O(R \cdot C \cdot 3^{L})O(L)O(L)
All paths in a mazeO(3R⋅C)O(3^{R \cdot C})O(R⋅C)O(R \cdot C)
Count right/down paths (DP)O(R⋅C)O(R \cdot C)O(C)O(C) with one row
N-QueensO(N!)O(N!)O(N)O(N)
Sudoku, mm empty cellsO(9m)O(9^{m})O(m)O(m) stack + O(81)O(81) sets
Word Search II (many words, trie)O(R⋅C⋅3L)O(R \cdot C \cdot 3^{L}) sharedO(total letters)O(\text{total letters})
These are worst-case bounds. Pruning does not change them, but in practice it decides whether the search finishes in milliseconds or never.

Speed-ups

Pruning and ordering tricks

  • Count before you search

    Word Search: compare letter counts first. A missing letter returns False in O(R⋅C+L)O(R \cdot C + L).

  • Rarer end first

    Reverse the word when its first letter is more common than its last. Fewer starts, same answer.

  • Fewest options first

    Sudoku and other constraint puzzles: fill the cell with the fewest candidates (MRV).

  • O(1) constraint checks

    Sets or bitmasks for columns, diagonals, rows and boxes instead of scanning the board.

  • Share prefixes

    Many words on one board: put them in a trie and walk the board once (Word Search II). Prune a trie branch once its words are found.

  • Use symmetry

    N-Queens: try only the left half of row 0 and mirror the results, halving the work.

Recap

Key takeaways

Key points

  • Grid backtracking = grid DFS where the visited mark is undone: Mark, Explore, Restore.
  • Mark before exploring, restore exactly the old value after exploring.
  • Check bounds before reading the cell; in Python negative indexes wrap silently.
  • Keep cells marked for reachability (flood fill); unmark for paths (Word Search, mazes).
  • Word Search: prune on letter counts and start from the rarer end; O(R · C · 3^L).
  • All paths in a maze: O(3^(R·C)); counting saves memory, not time.
  • If moves cannot loop back (right/down), count with DP in O(R · C) instead.
  • N-Queens: sets of c, r − c and r + c give O(1) checks; O(N!) worst case.
  • Sudoku: row, column and box sets, box = (r // b) · b + c // b, fewest candidates first.

Sources