Browse curriculum

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

Input:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output:true
Explain:

A → B → C → C → E → D, starting from the top-left cell.

Input:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output:true
Explain:

From the S on the right edge: down to E, then left to E.

Input:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output:false
Explain:

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.

  1. Try every start. Call backtrack(r, c, 0) from each cell in row order, and stop at the first that returns true.
  2. Finished? If i has run past the last letter, every letter is on the path: return true.
  3. 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.
  4. Mark. Write # into the cell, so no deeper call on this path can use it again.
  5. Explore. Try the four neighbours — down, up, right, left — with i + 1. The first one that returns true sets found and breaks.
  6. 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

A
B
C
C
E
D

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.