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.
See it run
Mark a cell, explore its neighbours, unmark it on the way back: watch word search, mazes, queens and Sudoku run on small grids.
Operations
Word Search with pruning
Trace a word through neighbouring cells without reusing one. Two cheap checks run before any search: does the board even have enough of each letter, and which end of the word is rarer? Then mark, explore four directions, unmark.
Step 1 of 9
Prune before searching: "ABCCC"
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| 0 | A | B | C | E |
| 1 | S | F | C | S |
| 2 | A | D | E | E |
C needed 3, have 2: False
Count the board's letters once. ABCCC needs three Cs, but the board has only two, at (0, 2) and (1, 2). exist returns False without a single dfs call. On big boards this check alone kills most impossible words.
Step 1: Prune before searching: "ABCCC"
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: the board lacks a letter 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 # every letter matched if not (0 <= r < rows and 0 <= c < cols) or board[r][c] != word[i]: return False # off the grid, wrong letter, or marked 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] # unmark return found return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))- Time
- O(R · C · 3ᴸ)
- Space
- O(L) recursion
- letter-count prune
- O(R · C + L), once
- branching after the first letter
- at most 3
- visited set
- none: mark in place with #
Two prunes cost almost nothing: compare letter counts, and start from whichever end of the word is rarer on the board.
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Forgetting to unmark
criticalThe mark is shared by every path. If a cell stays marked after its call returns, later paths and later start cells treat it as used. Word Search misses words that are there, and the maze lists only the first path.
Wrongboard[r][c] = "#"found = any(dfs(r + dr, c + dc, i + 1) for dr, dc in DIRS)return found # the # is never removedRightboard[r][c] = "#"found = any(dfs(r + dr, c + dc, i + 1) for dr, dc in DIRS)board[r][c] = word[i] # unmark before returningreturn foundReading the cell before the bounds check
criticalIn Python
board[-1]is the last row, not an error, so a missing or late bounds check silently wraps around the grid and finds paths that do not exist. At the far edge it crashes with IndexError instead.Wrongif board[r][c] != word[i] or not (0 <= r < rows and 0 <= c < cols): return FalseRightif not (0 <= r < rows and 0 <= c < cols) or board[r][c] != word[i]: return False # bounds first, so the index is always validRestoring the wrong value
majorUnmark must put back exactly what was there. Writing a fixed value like "." or 1 corrupts letters or walls. Save the old value, or restore from the word since the cell matched
word[i].Wrongboard[r][c] = "#"...board[r][c] = "." # the letter is gone for goodRightsaved = board[r][c]board[r][c] = "#"...board[r][c] = savedMarking after the recursive calls
majorThe mark must be in place before you explore neighbours, or a neighbour can step straight back onto this cell. With the word "ABA", the path A to B to the same A would be accepted.
Wrongfor dr, dc in DIRS: if dfs(r + dr, c + dc, i + 1): return Trueboard[r][c] = "#" # too lateRightboard[r][c] = "#" # mark firstfor dr, dc in DIRS: if dfs(r + dr, c + dc, i + 1): board[r][c] = word[i] return Trueboard[r][c] = word[i]Checking only one diagonal in N-Queens
majorA queen attacks along both diagonals. Tracking only r - c lets two queens share a down-left diagonal, so invalid boards are counted as solutions.
Wrongif c in cols or r - c in diag: continueRightif c in cols or r - c in diag or r + c in anti: continue # r - c: down-right, r + c: down-leftWrong Sudoku box index
majorr // 3 + c // 3gives the same number to different boxes (box (0, 1) and box (1, 0) both get 1). The box id must weight the box row by the number of boxes per row.Wrongbox = r // 3 + c // 3Rightbox = (r // 3) * 3 + c // 3 # 0..8, one id per 3 x 3 box
Interview tips
How to explain it
- Grid backtracking is DFS where the visited mark is part of the current path: mark on the way in, unmark on the way out.
- Each cell has at most 4 neighbours, and after the first step at most 3 are new.
- Name the bound: O(R · C · 3^L) for a word of length L, O(3^(R·C)) for all paths, O(N!) for N-Queens.
During the interview
- Ask: one path, all paths, or just a count? Can a cell be reused? Four or eight directions?
- Say whether you modify the grid in place and promise to restore it.
- Mention pruning before coding: letter counts, rarer end first, MRV for Sudoku.
- If moves only go right and down, say DP and skip backtracking.
Memory tricks
- MER: Mark, Explore, Restore.
- Bounds first, then the cell.
- r − c down-right, r + c down-left.
Watch out
- Restore exactly the old value.
- Flood fill keeps cells marked; path enumeration must unmark.
- Python's default recursion limit is 1,000: a path through every cell of a 40 × 40 grid exceeds it.