2Brute2Best
🔥0
07

Grid / path search (Backtracking Sub-pattern)

Walk from cell to cell (or node to node). Mark a cell when it joins the path and unmark it when you leave, so other paths can use it.

Signals in the problem statement
  • ›

    "all paths" from start to end in a maze

  • ›

    "the same cell may not be used more than once"

  • ›

    "all paths from 0 to n−1" in a DAG

What makes it different

Rat in a Maze lists every path; trying moves in the order D, L, R, U makes them come out already sorted. Word Search stops at the first match and marks cells in place with #. All Paths From Source to Target is a DAG, so there are no cycles and no visited set at all, just push and pop the path.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Rat in a Maze
    Basic Anchor·GeeksforGeeks
    Medium
  2. 2
    Word Search
    Basic Reinforcement·LeetCode #79
    Medium
  3. 3
    All Paths From Source to Target
    Slight Variation·LeetCode #797
    Medium

Template

grid-path-template.cpp
// Grid path: mark the cell on the way in, unmark on the way out,
// so other paths may still pass through it later (Word Search).
bool dfs(vector<vector<char>>& g, const string& word, int i, int r, int c) {
    if (i == (int)word.size()) return true;              // every letter matched
    if (r < 0 || c < 0 || r >= (int)g.size() || c >= (int)g[0].size() || g[r][c] != word[i])
        return false;                                    // off the grid, used, or wrong letter
    char saved = g[r][c];
    g[r][c] = '#';                                       // mark: in use on this path
    bool found = dfs(g, word, i + 1, r + 1, c) || dfs(g, word, i + 1, r - 1, c) ||
                 dfs(g, word, i + 1, r, c + 1) || dfs(g, word, i + 1, r, c - 1);
    g[r][c] = saved;                                     // unmark: free for other paths
    return found;
}

bool exist(vector<vector<char>>& board, const 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, 0, r, c)) return true;
    return false;
}
Remember this · Backtracking
Trigger
"All subsets / permutations / combinations", place items under rules (N-Queens, Sudoku), find a path in a grid.
Think
At each step, what are my choices, and how do I undo a choice?
Key question
What is my state, when is it complete, and when do I prune?