Module 9 · Backtracking · Backtracking: Inclusion–Exclusion

Word search

Every cell is tried as the start of the word. search(cell, index) checks that the cell holds word[index] and isn't already used, marks it, and asks its four neighbours (down, up, right, left) for the next letter. If none of them can carry on, the cell is unmarked on the way back, so a different path may use it.

The trail joins the letters matched so far. A red tile didn't match, or was already on the path. word points at the letter being looked for; the call stack holds one search per letter matched.