Instructions
You are given a grid board of letters and a list words of distinct words. Each cell of the grid holds one lowercase letter, as a string of length 1.
A word can be built from the grid if there is a path of cells that spells it. A path starts at any cell and moves, one step at a time, to a cell directly up, down, left or right of the current cell. Diagonal moves are not allowed. In one path, each cell can be used at most once. Different words may use the same cells.
Return every word from words that can be built, sorted in alphabetical order. Each word appears at most once in the answer. If no word can be built, return an empty list.
Hint: searching for each word on its own repeats a lot of work. Put all the words in a trie (a prefix tree). Then run one backtracking search from every cell, and walk down the trie as you walk the grid. Stop a path as soon as its letters are not the start of any word.
Examples
Example 1
- Input:
- [["l","o","g"],["i","n","e"],["t","a","r"]], ["tar","log","line","gone","lint","tan"]
- Output:
- ["gone","line","log","tan","tar"]
"log" is the top row. "line" goes l, i (down), n (right), e (right). "gone" goes g, o (left), n (down), e (right). "tar" is the bottom row. "tan" goes t, a (right), n (up). "lint" fails: after "l", "i" and "n", the only "t" is in the bottom-left corner, which is not next to "n".
Example 2
- Input:
- [["a","b"],["b","a"]], ["abab","aba","abba","aa"]
- Output:
- ["aba","abab"]
Walking around the 2 x 2 square from the top-left "a" (right, down, left) gives "abab", and its first three cells give "aba". The two "b" cells sit on a diagonal, so they are not next to each other and "abba" cannot be built. The two "a" cells are also on a diagonal, so "aa" cannot be built.
Example 3
- Input:
- [["x","y","z"]], ["zyx","xz","yy"]
- Output:
- ["zyx"]
"zyx" reads the row from right to left. "xz" needs "x" next to "z", but "y" is between them. "yy" needs two "y" cells, and there is only one.
Constraints
1 <= board.length <= 51 <= board[i].length <= 5, and every row has the same length.board[i][j]is a single lowercase English letter.1 <= words.length <= 101 <= words[i].length <= 7words[i]has only lowercase English letters, and all words are different.
3 examples run when you press Run. Submit checks every hidden test too.
- Input:
- [["l","o","g"],["i","n","e"],["t","a","r"]], ["tar","log","line","gone","lint","tan"]
- Expected:
- ["gone","line","log","tan","tar"]
- Input:
- [["a","b"],["b","a"]], ["abab","aba","abba","aa"]
- Expected:
- ["aba","abab"]
- Input:
- [["x","y","z"]], ["zyx","xz","yy"]
- Expected:
- ["zyx"]
Run checks your code against the 3 examples. Submit checks it against all 123 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.