Learn / Recursion and backtracking
Word search
To find a word in a grid, start from every cell that matches the first letter and grow the match one neighbour at a time, never reusing a cell on the same path. Marking a cell in place (and restoring it on the way back) avoids a separate visited array. Straight-line searches need no backtracking at all.
How to recognise it
- A word must be traced through a grid of letters, along neighbouring cells.
- The question asks whether it exists, how many ways, or where it starts.
The idea in one picture
Put your finger on a cell with the first letter. Move it to a neighbour with the second letter, then the third, never touching a cell twice. If you get stuck, lift your finger back one cell and try another neighbour.
Template
function match(r, c, i):
if (r, c) is outside or grid[r][c] != word[i]: return false
if i == last index: return true
saved = grid[r][c]; grid[r][c] = '#'
found = match on the four neighbours with i + 1
grid[r][c] = saved
return found
Three questions
| Question | Combine neighbours with | Directions |
|---|---|---|
| Does the word exist? | or (stop early) | 4, path may turn |
| How many paths spell it? | + | 4, path may turn |
| Where does it start in a straight line? | none: loop over the letters | 8, no turning |
Common mistakes
- Forgetting to restore the letter, which breaks later searches.
- Reusing a cell within one path.
- Mixing up "path may turn" problems with straight-line problems.
Problems
- Word Searchmediumguide ready
- Count of number of given string in 2D character arraymediumguide ready
- Search a Word in a 2D Grid of charactersmediumguide ready