Skip to content

Commit 50815a3

Browse files
authored
Create Word Search II.java
1 parent 40ed485 commit 50815a3

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

hard/Word Search II.java

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
//212. Word Search II
2+
class TrieNode {
3+
public TrieNode[] children = new TrieNode[26];
4+
public String word;
5+
}
6+
7+
class Solution {
8+
public List<String> findWords(char[][] board, String[] words) {
9+
for (final String word : words)
10+
insert(word);
11+
12+
List<String> ans = new ArrayList<>();
13+
14+
for (int i = 0; i < board.length; ++i)
15+
for (int j = 0; j < board[0].length; ++j)
16+
dfs(board, i, j, root, ans);
17+
18+
return ans;
19+
}
20+
21+
private TrieNode root = new TrieNode();
22+
23+
private void insert(final String word) {
24+
TrieNode node = root;
25+
for (final char c : word.toCharArray()) {
26+
final int i = c - 'a';
27+
if (node.children[i] == null)
28+
node.children[i] = new TrieNode();
29+
node = node.children[i];
30+
}
31+
node.word = word;
32+
}
33+
34+
private void dfs(char[][] board, int i, int j, TrieNode node, List<String> ans) {
35+
if (i < 0 || i == board.length || j < 0 || j == board[0].length)
36+
return;
37+
if (board[i][j] == '*')
38+
return;
39+
40+
final char c = board[i][j];
41+
TrieNode child = node.children[c - 'a'];
42+
if (child == null)
43+
return;
44+
if (child.word != null) {
45+
ans.add(child.word);
46+
child.word = null;
47+
}
48+
49+
board[i][j] = '*';
50+
dfs(board, i + 1, j, child, ans);
51+
dfs(board, i - 1, j, child, ans);
52+
dfs(board, i, j + 1, child, ans);
53+
dfs(board, i, j - 1, child, ans);
54+
board[i][j] = c;
55+
}
56+
}

0 commit comments

Comments
 (0)