Copy /**
* Time complexity :
* Space complexity :
*/
class Solution {
class TrieNode {
TrieNode[] children = new TrieNode[26];
String word = null;
}
public List<String> findWords(char[][] board, String[] words) {
List<String> result = new ArrayList();
if(board == null || board.length == 0) {
return result;
}
TrieNode trieNode = buildTrie(words);
int row = board.length,
col = board[0].length;
for(int r = 0; r < row; r++) {
for(int c = 0; c < col; c++) {
dfs(board, r, c, trieNode, result);
}
}
return result;
}
private void dfs(char[][] board,
int r,
int c,
TrieNode trieNode,
List<String> result
) {
int row = board.length,
col = board[0].length;
if(r < 0 || r >= row || c < 0 || c >= col) return;
if(board[r][c] == '#' ||
trieNode.children[board[r][c]-'a'] == null) return;
char ch = board[r][c];
trieNode = trieNode.children[board[r][c]-'a'];
if(trieNode.word != null) {
result.add(trieNode.word);
trieNode.word = null;
}
board[r][c] = '#';
dfs(board, r+1, c, trieNode, result);
dfs(board, r-1, c, trieNode, result);
dfs(board, r, c+1, trieNode, result);
dfs(board, r, c-1, trieNode, result);
board[r][c] = ch;
}
private TrieNode buildTrie(String[] words) {
TrieNode trieNode = new TrieNode();
for(String word: words) {
TrieNode currNode = trieNode;
for(char ch: word.toCharArray()) {
if(currNode.children[ch-'a'] == null) {
currNode.children[ch-'a'] = new TrieNode();
}
currNode = currNode.children[ch-'a'];
}
currNode.word = word;
}
return trieNode;
}
}