Word Search II
Problem
You are given a grid of letters and a list of words. Find every word from the list that can be traced as a path through adjacent grid cells (up, down, left, right), reusing no cell within a single word's path, and return all words from the list that can be found this way.
Example. On a grid containing the letters to spell "oath" and "eat" along adjacent cells, both words would be returned if their letter paths exist, while a word like "pea" is excluded if no adjacent path spells it.
Key idea
Searching for each word independently means a fresh grid exploration per word, repeating the same work over and over. That is wasteful when several words share starting letters. The fix is to search for all words at once: combine the dictionary into a single trie, then walk the grid once, following trie edges instead of chasing one target word.
Start a depth-first search from every cell. At each step, check whether the current letter has a matching child in the trie; if not, the path cannot spell any dictionary word and stops there. If it does, move to that child, mark the cell visited so the path cannot revisit it, and explore the neighbors. Whenever the current trie node marks a completed word, record it. Because branches sharing a prefix are explored together, the search prunes as soon as a partial path stops matching any word.
Solution
Complexity
- Time: O(rows × cols × 4^maxLen) in the worst case, where maxLen is the longest word, since each cell can start a bounded-depth backtracking search; trie pruning cuts this substantially in practice.
- Space: O(total characters in the dictionary) for the trie, plus O(maxLen) recursion depth.
Watch out for
- Unmark a visited cell after backtracking out of it, or later paths through that cell will be wrongly blocked.
- Avoid returning the same word twice; once found, removing or flagging its trie ending prevents duplicate matches from overlapping paths.
Pattern
This pairs grid backtracking with a shared trie, a pattern for any problem that checks a grid against many target patterns at once rather than one at a time; the same combination shows up in boggle-style word games and multi-pattern string matching.