1780. Spelling Path Count
A sign painter lays letter tiles on a small board stored in grid and wants to know how many different ways a name can be read off it. A reading starts on any tile and then repeatedly steps to any of the 8 neighbouring tiles (horizontal, vertical or diagonal), collecting one letter per tile.
Return the number of distinct cell sequences whose letters spell word exactly, where no tile may appear twice in the same sequence. Two sequences are different when they differ in at least one cell, even if they spell the same letters. Return 0 when the word cannot be spelled. Use depth-first search that marks a tile while it is on the current path and unmarks it on the way back. Intended complexity: O(rows * cols * 8^L) time with L the word length, and O(rows * cols) space.
Example 1
- Input:
- grid = [["C","A","T"],["O","T","S"],["D","A","R"]]word = "CAT"
- Output:
- 2
- Explanation:
The word starts at C, goes to the A diagonally or beside it, then to a T; two distinct cell sequences spell it.
Example 2
- Input:
- grid = [["A","B"],["B","A"]], word = "ABA"
- Output:
- 4
- Explanation:
Every route A-B-A uses both A cells and one of the two B cells, giving four sequences.
Example 3
- Input:
- grid = [["X","Y"],["Y","X"]], word = "XYZ"
- Output:
- 0
- Explanation:
No Z exists in the grid, so no sequence spells the word and the answer is 0.
Constraints
1 ≤ rows, cols ≤ 5
1 ≤ word.length ≤ 6
All letters are uppercase English letters
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(rows * cols * 8^L)
- Space
- O(rows * cols)