Chat app~25 min2s · 256 MBtarget O(cells × 3^len) time, O(cells) spaceclassic twin: lc-79backtracking
A chat app has a word game. The board is a grid of letters. A player spells a word by tapping letters that touch side to side, and never taps the same cell twice in one word.
The game gives points for every different way to tap the word.
Your team lead says: For a word on a board, how many different tap paths spell it?
Write count_word_paths(grid, word).
grid is a list of rows of lowercase letters, and every row has the same length.word in order.Input: grid = ["tea", "ate"], word = "tea"
Output: 3The paths are listed by their cells, as (row, column). The search starts a path at every cell, and stops it on the first wrong letter.
| Path number | Cells | Letters |
|---|---|---|
| 1 | (0, 0), (0, 1), (0, 2) | t, e, a |
| 2 | (1, 1), (0, 1), (0, 2) | t, e, a |
| 3 | (1, 1), (1, 2), (0, 2) | t, e, a |
The search makes 16 calls. The answer is 3.
Input: grid = ["aaa", "aaa"], word = "aaaa"
Output: 28Every cell holds a. Each path of 4 different cells, moving by sides, counts once. The search finds 28 of them.
Input: grid = ["ab", "cd"], word = "ad"
Output: 0The letters a and d sit on a diagonal, and a diagonal is not a move. No path of two touching cells spells ad.
1 ≤ grid.length ≤ 81 ≤ grid[i].length ≤ 8, and every row has the same length1 ≤ word.length ≤ 16a to zA walk that checks no letters has up to 4 × 3^13 = 6,377,292 continuations from one start cell for a word of 14 letters. Checking each letter as you go stops almost all of them. The first large test makes 754,981 calls and finds 68,192 paths. The recursion is at most 16 calls deep.