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

QuestionCombine neighbours withDirections
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 letters8, 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

0 of 3 solved

Check yourself

Why temporarily replace a cell's letter with a marker like '#' during the search?

When searching only straight lines in 8 directions, is backtracking needed?

To count every way of tracing a word, what changes compared with checking that it exists?