Grid backtracking
medium 25 minGrid 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
Grid backtracking in 75 seconds
1:26Reel
How it works
Step through the idea, or press Play.
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 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 , up , right , left . Restore the cell before returning.
One call of a grid backtracking search
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']]ok decides if a cell may extend the path; the mark and restore bracket the recursion.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: , since each cell is visited once in total.
| How to mark | Undo | When to use |
|---|---|---|
Overwrite in place: board[r][c] = "#" | board[r][c] = saved | Mutable 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] = False | Many lookups, a bit faster than a set |
| Bitmask over cells | mask ^ (1 << (r * C + c)) | Tiny grids where the mask can be memoised |
# 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
ABCE / SFCS / ADEE, ABCCED has two possible starts (two As) but its reverse DECCBA has one (one D).Cost of one Word Search
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")) # TrueWorked 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.
| Word | Prune | What the search does | Result |
|---|---|---|---|
ABCCC | needs 3 C, board has 2 | No search at all. | False |
ABCCED | A ×2, D ×1: search DECCBA | Start at the only D (2, 1). E right, C up, C up, B left, A left. Six cells marked, then all six restored. | True |
SEE | S ×2, E ×3: keep | S 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 |
ABCB | none applies | A, B, C match; the only B next to C is already marked on this path. | False |
CODE on CODE / ABCD / EFGH | C ×2, E ×2: keep | From (0, 0): down A fails, up is off the grid, right O, right D, right E. | True |
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 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.
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']| Moment | Path so far | What happens |
|---|---|---|
| 1 | DDRDRR | Down, down, wall below so right, down, right, right: the exit. List it. |
| 2 | DDR + U | Back up to (2, 1), unmarking (3, 2) and (3, 1). Up to (1, 1): every neighbour is marked or a wall. Dead end, unmark. |
| 3 | D + R | Unwind to (1, 0) and go right. (1, 1) is free again because it was unmarked. |
| 4 | DRDDRR | Down, down, right, right: the exit again, through (2, 1), (3, 1), (3, 2), cells the first path also used. |
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 , as in Unique Paths. With four directions it does, because the cells already used block some futures.
Right and down only: a recurrence
| Grid | Right / down paths (DP) | 4-direction simple paths (backtracking) |
|---|---|---|
| 3 × 3 | 6 | 12 |
| 4 × 4 | 20 | 184 |
| 5 × 5 | 70 | 8,512 |
| 6 × 6 | 252 | 1,262,816 |
Count, list, or just check?
Pattern 4
N-Queens with column and diagonal sets
Put one queen per row, so row only chooses a column . Scanning the board to see if is attacked costs . Three sets make it : used columns, used values of , used values of .
Why two diagonal sets are enough
The O(1) safety check
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]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 . 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?
Sudoku solver
Complexity
Bounds you should be able to state
All simple paths on an R × C grid
N-Queens
| Problem | Time | Space |
|---|---|---|
| Word Search, word of length | ||
| All paths in a maze | ||
| Count right/down paths (DP) | with one row | |
| N-Queens | ||
| Sudoku, empty cells | stack + sets | |
| Word Search II (many words, trie) | shared |
Speed-ups
Pruning and ordering tricks
Count before you search
Word Search: compare letter counts first. A missing letter returns False in .
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.