25/38
Part 5 of 7 · Graphs and backtrackingLearn and do

In word search, a word that almost fits is the slow case

For word search, a path can start at any of the RCRC cells. A word of L≥2L \ge 2 letters has at most 4⋅3L−24 \cdot 3^{L-2} paths from each start: 4 choices for the first step, then 3 for each step after, since one of the four neighbors is the cell you came from. That's O(RC⋅3L)O(RC \cdot 3^L).

A hard case is a 5 by 5 grid of As and a word of As with a B at the end. Every path of As stays alive, and the B is never there. Counting every call to match, the function this step's task asks for, tries outside the grid included:

Word lengthCalls to match
41,197
66,909
831,965
10122,685

The 10-letter word took 33.4 ms.

In the editor, write match(r, c, i) inside has_word(grid, word). It looks for three words on the classic grid.