Find if a word exists in a 2D character grid using DFS with backtracking
N × M cells as potential starting positionsL (word length), giving 4L branchesThe outer loop tries every cell as a potential word start. From each cell, the DFS branches into at most 4 directions at each character position. The exponential factor 4L dominates, but in practice the search tree is heavily pruned by character mismatches and visited-cell checks, making the average case much faster.
Backtracking is essential: by restoring cells after exploration, the algorithm allows different starting positions to reuse the same cells in different paths. This correctness guarantee comes at the cost of potentially re-exploring cells across different starting points.
L (word length)'#' avoids a separate visited arrayThe algorithm modifies the board in-place to mark visited cells, restoring them on backtrack. This means no separate visited set is needed. The only space cost is the recursion stack, which goes at most L levels deep (one level per character in the word).
In-place marking is a classic space optimization for grid DFS. By temporarily mutating the input (board[r][c] = '#'), we get O(1) visited tracking per cell. The restore step (board[r][c] = word[k]) ensures the board is unchanged after the function returns.