212 Word Search 2
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
Output: ["eat","oath"]
Trie + DFS
First use String[] words to build a trie tree to store all the words
Then use dfs in the matrix
Time: O(m * n * TrieNode)
Space O(TrieNode)
// time : O(n) n: word.length();
// O\(num of TrieNode \* 26\) = O\(num of Words \* word.length\(\) \* 26\)
/\*\* Inserts a word into the trie. \*/
class Solution {
public List<String> findWords(char[][] board, String[] words) {
List<String> ans = new ArrayList<>();
TrieNode root = new TrieNode();
root = buildTrie(words);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
dfs(board, i, j, root, ans);
}
}
return ans;
}
class TrieNode {
TrieNode[] children = new TrieNode[26];
String isWord = null;
}
public TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode();
for (String word : words) {
TrieNode curt = root;
for (char c : word.toCharArray()) {
int i = c - 'a';
if(curt.children[i] == null) {
curt.children[i] = new TrieNode();
}
curt = curt.children[i];
}
curt.isWord = word;
}
return root;
}
public void dfs(char[][] board, int x, int y, TrieNode root, List<String> ans) {
int rows = board.length;
int cols = board[0].length;
if (x < 0 || x >= rows || y < 0 || y >= cols) {
return;
}
char c = board[x][y];
if (c == '#' || root.children[c - 'a'] == null) {
return;
}
root = root.children[c - 'a']; // you must change the root
if (root.isWord != null) {
ans.add(root.isWord);
root.isWord = null;
}
board[x][y] = '#';
dfs(board, x + 1, y, root, ans);
dfs(board, x - 1, y, root, ans);
dfs(board, x, y + 1, root, ans);
dfs(board, x, y - 1, root, ans);
board[x][y] = c;
}
}