← Back to Visualizer Gallery
Traversal · Backtracking on a Grid LeetCode 79

Word Search / in-place masking & restoration

Enumerate candidate paths through DFS with in-place character masking: mutate board[r][c] = '#' to prevent cycle reuse, recurse through neighbors, and strictly restore board[r][c] = temp upon unwind.

Execution Stage

idle
INVARIANT Backtracking Mark-and-Restore Invariant: Mutating board[r][c] = '#' eliminates cycles in $O(1)$ space. Every branch MUST guarantee unwinding back to board[r][c] = originalChar to preserve grid integrity.
Press Run to trace DFS word search.
RECURSION CALL STACK
0 / 0
Speed

Java · Reference Algorithm

INTERVIEW SCRIPT

How to Present Word Search to an Interviewer

1. In-Place Masking vs boolean[][]

"Instead of allocating an $O(mn)$ boolean array or re-instantiating state, I mutate board[r][c] = '#' (or XOR with 256) before branching, and restore the original char upon return. This uses $O(1)$ extra heap space."

2. Backtracking Symmetry

"Every cell marked as visited MUST be unconditionally restored during recursion unwind. Even when all 4 cardinal directions fail, restoring the cell allows alternate valid paths to traverse through it."

3. Complexity & Branching Factor

"From the starting letter, we branch up to 4 ways. For all subsequent letters $k \ge 1$, we cannot revisit our parent cell, so the branching factor is at most 3. Worst-case time is $O(M \cdot N \cdot 3^L)$ where $L$ is word length; stack space is $O(L)$."

4. Production Pruning Heuristic

"Before searching, verify character counts in the board. If the word's tail character occurs less frequently than its head, reversing the word prunes the search tree exponentially earlier!"

Word Search (LC 79) — Backtracking on grid with in-place cell masking · Time $O(M \cdot N \cdot 3^L)$, Space $O(L)$.