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.

3 variations · 5 problems · 3 with animated walkthroughs

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

2D Matrix Backtracking
// 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;
}

The variations

  1. 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
  2. 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
  3. 3More practice

    More problems that use this pattern. Try them once the variations above feel easy.

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