Word search on a board
Challenge · Write code · about 25 min
A board is a list of equal-length strings, one per row. Return every word of words that can be spelled by a path of adjacent cells. Adjacent means up, down, left or right. A cell may be used only once per word. The result may be in any order.
Put the words in a trie and walk the board with DFS. Stop a path as soon as the trie has no edge for the next letter.
Example 1
Input:
[["ca","tr"],["cat","car","cart"]]
Output:
["car","cart"]
car and cart fit the board. cat needs t next to a, but they only touch diagonally.
Example 2
Input:
[["ab","cd"],["abdc","acdb","abcd"]]
Output:
["acdb","abdc"]
abcd would need b and c to touch.
Constraints
- 1 ≤ board.length ≤ 12 and 1 ≤ board[i].length ≤ 12
- 0 ≤ words.length ≤ 2,000
- Words are different, each 1 to 8 lowercase letters
Learn the idea first: Trie applications: autocomplete, word search, XOR maximum, a visual lesson.
More Trie applications: autocomplete, word search, XOR maximum problems
- Replace words Warm-up
- Autocomplete top-3 Standard
- Maximum XOR pair Standard
- Trace the XOR walk Standard