Skip to content

Commit e9f54b5

Browse files
HARD/src/hard/WordSearchII.java
1 parent f0acddd commit e9f54b5

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

HARD/src/hard/WordSearchII.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package hard;
2+
3+
import java.util.*;
4+
5+
public class WordSearchII {
6+
7+
public List<String> findWords(char[][] board, String[] words) {
8+
TrieNode root = buildTrie(words);
9+
List<String> result = new ArrayList();
10+
for(int i = 0; i < board.length; i++){
11+
for(int j = 0; j < board[0].length; j++){
12+
dfs(root, board, i, j, result);
13+
}
14+
}
15+
return result;
16+
}
17+
18+
private void dfs(TrieNode root, char[][] board, int i, int j, List<String> result){
19+
char c = board[i][j];
20+
21+
if(c == '#' || root.children[c - 'a'] == null) return;
22+
23+
if(root.children[c - 'a'].word != null){
24+
result.add(root.children[c - 'a'].word);
25+
root.children[c - 'a'].word = null;//de-duplicate
26+
}
27+
board[i][j] = '#';//mark it as visited to avoid cycles
28+
if(i > 0) dfs(root.children[c - 'a'], board, i-1, j, result);
29+
if(j > 0) dfs(root.children[c - 'a'], board, i, j-1, result);
30+
if(i+1 < board.length) dfs(root.children[c - 'a'], board, i+1, j, result);
31+
if(j+1 < board[0].length) dfs(root.children[c - 'a'], board, i, j+1, result);
32+
33+
board[i][j] = c;
34+
}
35+
36+
private TrieNode root;
37+
38+
class TrieNode{
39+
String word;
40+
TrieNode[] children = new TrieNode[26];
41+
}
42+
43+
private TrieNode buildTrie(String[] words){
44+
TrieNode root = new TrieNode();
45+
for(String word : words){
46+
char[] chars = word.toCharArray();
47+
TrieNode temp = root;
48+
for(char c : chars){
49+
if(temp.children[c - 'a'] == null){
50+
temp.children[c - 'a'] = new TrieNode();
51+
}
52+
temp = temp.children[c - 'a'];
53+
}
54+
temp.word = word;
55+
}
56+
return root;
57+
}
58+
59+
}

0 commit comments

Comments
 (0)