Music streaming app~45 min2s · 256 MBtarget O(cells × 8 × 7^(L-1)) at worst, pruned by the trie time, O(total word length) spaceclassic twin: lc-212backtracking · trie
A music app has a word-hunt game. The board is a grid of letters, and the player gets a list of tag words, such as the names of moods. The player must find which of the words can be traced in the grid.
A word is traced by tapping cells one after another. Each next cell touches the one before it, along a side or at a corner. A cell can be tapped once in one word.
Write find_words(grid, words).
grid is a list of rows of lowercase letters. Every row has the same length.words is a list of different lowercase words.Input: grid = ["pla","oyr","tud"], words = ["play","plot","pour","lord","dry","ray","road"]
Output: ["dry","play","plot","pour","ray"]The solution puts all the words into a tree of letters, then starts a search from every cell. The search only follows a letter that continues a word in the tree.
| Start cell (row, column) | Letter | Words recorded |
|---|---|---|
| (0, 0) | p |
play, plot, pour |
| (1, 2) | r |
ray |
| (2, 2) | d |
dry |
The word lord starts at l but no r touches its o. The word road needs an o next to the r, and there is none.
Input: grid = ["ab","cd"], words = ["abdc","acbd","dcba","abcd"]
Output: ["abcd","abdc","acbd","dcba"]In a two by two grid every cell touches every other cell, so every order of the four letters can be traced.
Input: grid = ["a"], words = ["aa","b"]
Output: []The word aa would use the only cell twice, and b is not in the grid.
1 ≤ rows, columns ≤ 101 ≤ len(words) ≤ 3,000, and every word has 1 to 10 lowercase lettersA walk of 10 cells can follow up to 8 × 7^9 chains from one start, which is over 300,000,000. Tracing each of 3,000 words on its own repeats the same walks again and again. Words that begin alike must share one walk.