FAANGPrep Sprint
Word Search
Find whether a word can be traced through adjacent cells of a letter grid, marking each cell on the way down and restoring it on the way back.
Examples
A → B → C → C → E → D, starting from the top-left cell.
From the S on the right edge: down to E, then left to E.
The second B would have to be the same cell as the first.
Problem Understanding
Return true if word can be spelled out on the m x n letter grid board by stepping from each letter to the next through cells that touch up, down, left or right.
Diagonal steps are not allowed, and no cell may be used twice in the same word.
Algorithm Strategy
Grid DFS with an undo — backtracking on a board.
- Try every start. Call
backtrack(r, c, 0)from each cell in row order, and stop at the first that returns true. - Finished? If
ihas run past the last letter, every letter is on the path: return true. - Reject. Return false for a position off the board, or a cell whose letter is not
word[i]— which includes a cell marked#, because#is never a letter of the word. - Mark. Write
#into the cell, so no deeper call on this path can use it again. - Explore. Try the four neighbours — down, up, right, left — with
i + 1. The first one that returns true setsfoundand breaks. - Unmark. Write the letter back before returning
found.
Marking the board in place is what saves a separate visited set; writing the letter back is what makes that safe.
Interactive Visualization
# = ON THE CURRENT PATH · ARROW = THE CALL ABOUT TO RUN · RED = REJECTED
START FROM THIS CELL
matched
0/6
depth
0
Answer
—
word
call stack
No backtrack running
Start from (0, 0): call backtrack(0, 0, 0), looking for "A"
Next
(0, 0) is "A" = word[0] — mark it # so this path cannot reuse it
board
word
The board is drawn exactly as the code holds it. A cell on the current path shows #, because that is what the code has written into it; the letter comes back, in amber, on the step that writes it back. The arrow is the call about to be made, a rejected cell flashes red with the reason, and a call that steps off the board lands on an empty cell outside it before returning.
Try Undo matters: the first path from the top-left A fails, and the second start only succeeds because the first one wrote its letters back.
