Recursion & Backtracking · Pattern 5 of 9
Grid backtracking: paths and boards
On a grid, the choice is which neighbour to step to or which value to write in a cell. Mark the cell, recurse, and restore it, so other paths can use it again.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Find a path on a grid that spells a word or visits cells once
- Fill a board so rows, columns and boxes stay valid
- Explore an unknown space and come back to where you started
The template
// word search: walk the grid, marking cells on the current path
boolean exist(char[][] board, String word) {
for (int r = 0; r < board.length; r++)
for (int c = 0; c < board[0].length; c++)
if (dfs(board, word, r, c, 0)) return true;
return false;
}
boolean dfs(char[][] b, String w, int r, int c, int k) {
if (k == w.length()) return true; // matched every letter
if (r < 0 || c < 0 || r >= b.length || c >= b[0].length || b[r][c] != w.charAt(k)) return false;
char saved = b[r][c];
b[r][c] = '#'; // on the path: do not reuse
boolean found = dfs(b, w, r + 1, c, k + 1) || dfs(b, w, r - 1, c, k + 1)
|| dfs(b, w, r, c + 1, k + 1) || dfs(b, w, r, c - 1, k + 1);
b[r][c] = saved; // restore
return found;
}
// count N-Queens boards: bitmasks for columns and both diagonals
int totalNQueens(int n) { return count(n, 0, 0, 0, 0); }
int count(int n, int row, int cols, int d1, int d2) {
if (row == n) return 1;
int total = 0;
int free = ~(cols | d1 | d2) & ((1 << n) - 1); // safe columns in this row
while (free != 0) {
int bit = free & -free; // lowest safe column
free -= bit;
total += count(n, row + 1, cols | bit, (d1 | bit) << 1, (d2 | bit) >> 1);
}
return total;
} def exist(board, word): # word search
m, n = len(board), len(board[0])
def dfs(r, c, k):
if k == len(word):
return True # matched every letter
if not (0 <= r < m and 0 <= c < n) or board[r][c] != word[k]:
return False
saved, board[r][c] = board[r][c], '#' # on the path: do not reuse
found = (dfs(r + 1, c, k + 1) or dfs(r - 1, c, k + 1)
or dfs(r, c + 1, k + 1) or dfs(r, c - 1, k + 1))
board[r][c] = saved # restore
return found
return any(dfs(r, c, 0) for r in range(m) for c in range(n))
def total_n_queens(n): # bitmasks for columns and both diagonals
full = (1 << n) - 1
def count(row, cols, d1, d2):
if row == n:
return 1
total, free = 0, ~(cols | d1 | d2) & full # safe columns in this row
while free:
bit = free & -free # lowest safe column
free -= bit
total += count(row + 1, cols | bit, ((d1 | bit) << 1) & full, (d2 | bit) >> 1)
return total
return count(0, 0, 0, 0) // word search: walk the grid, marking cells on the current path
bool dfs(vector<vector<char>>& b, const string& w, int r, int c, int k) {
if (k == (int)w.size()) return true; // matched every letter
if (r < 0 || c < 0 || r >= (int)b.size() || c >= (int)b[0].size() || b[r][c] != w[k]) return false;
char saved = b[r][c];
b[r][c] = '#'; // on the path: do not reuse
bool found = dfs(b, w, r + 1, c, k + 1) || dfs(b, w, r - 1, c, k + 1)
|| dfs(b, w, r, c + 1, k + 1) || dfs(b, w, r, c - 1, k + 1);
b[r][c] = saved; // restore
return found;
}
bool exist(vector<vector<char>>& board, string word) {
for (int r = 0; r < (int)board.size(); r++)
for (int c = 0; c < (int)board[0].size(); c++)
if (dfs(board, word, r, c, 0)) return true;
return false;
}
// count N-Queens boards: bitmasks for columns and both diagonals
int countQueens(int n, int row, int cols, int d1, int d2) {
if (row == n) return 1;
int total = 0;
int free = ~(cols | d1 | d2) & ((1 << n) - 1); // safe columns in this row
while (free) {
int bit = free & -free; // lowest safe column
free -= bit;
total += countQueens(n, row + 1, cols | bit, (d1 | bit) << 1, (d2 | bit) >> 1);
}
return total;
}
int totalNQueens(int n) { return countQueens(n, 0, 0, 0, 0); } // word search: walk the grid, marking cells on the current path
function exist(board, word) {
const m = board.length, n = board[0].length;
function dfs(r, c, k) {
if (k === word.length) return true; // matched every letter
if (r < 0 || c < 0 || r >= m || c >= n || board[r][c] !== word[k]) return false;
const saved = board[r][c];
board[r][c] = '#'; // on the path: do not reuse
const found = dfs(r + 1, c, k + 1) || dfs(r - 1, c, k + 1)
|| dfs(r, c + 1, k + 1) || dfs(r, c - 1, k + 1);
board[r][c] = saved; // restore
return found;
}
for (let r = 0; r < m; r++) for (let c = 0; c < n; c++) if (dfs(r, c, 0)) return true;
return false;
}
// count N-Queens boards: bitmasks for columns and both diagonals
function totalNQueens(n) {
const full = (1 << n) - 1;
function count(row, cols, d1, d2) {
if (row === n) return 1;
let total = 0, free = ~(cols | d1 | d2) & full; // safe columns in this row
while (free) {
const bit = free & -free; // lowest safe column
free -= bit;
total += count(row + 1, cols | bit, ((d1 | bit) << 1) & full, (d2 | bit) >> 1);
}
return total;
}
return count(0, 0, 0, 0);
} The variations
-
1Walk a path through the grid
Start from every matching cell, step to the four neighbours, and mark cells on the current path so you never reuse one. When the robot cannot see the grid, track cells by relative position and walk back after each step.
Now you solve -
2Fill a board under constraints
Pick the next empty slot (a row for a queen, a cell for a digit), try each value that breaks no rule, recurse, and undo. Sets or bitmasks per row, column, box or diagonal make the rule check O(1).
Now you solve -
3More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems- Rat in a Maze Medium Stuck? ▶ video
Mistakes to avoid
- Marking a cell visited for good (like a BFS) instead of restoring it after the call: a later path may need that cell.
- Sudoku: trying a value without checking its row, column and 3 × 3 box first, or not undoing the cell when the branch fails.
- Robot Room Cleaner: after exploring a neighbour you must physically move back (turn twice, move, turn twice), not just return.
Lesson done
Next: Choice per position: menus and cuts →Mark it done once you can write the template from memory and you have solved the worked examples yourself.