forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWord Search II.java
More file actions
66 lines (53 loc) · 1.67 KB
/
Word Search II.java
File metadata and controls
66 lines (53 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Solution {
public List<String> findWords(char[][] board, String[] words) {
List<String> result = new ArrayList<>();
TrieNode root = buildTrie(words);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
helper(board, i, j, root, result);
}
}
return result;
}
private void helper(char[][] board, int i, int j, TrieNode root, List<String> result) {
if (i < 0 || i >= board.length || j >= board[i].length || j < 0) {
return;
}
char c = board[i][j];
if (c == '@' || root.next[c - 'a'] == null) {
return;
}
root = root.next[c - 'a'];
if (root.word != null) {
result.add(root.word);
root.word = null;
}
// Choose
board[i][j] = '@';
// Explore
helper(board, i + 1, j, root, result);
helper(board, i, j + 1, root, result);
helper(board, i, j - 1, root, result);
helper(board, i - 1, j, root, result);
// Un-choose
board[i][j] = c;
}
private TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode();
for (String word : words) {
TrieNode temp =root;
for (char c : word.toCharArray()) {
if (temp.next[c - 'a'] == null) {
temp.next[c - 'a'] = new TrieNode();
}
temp = temp.next[c - 'a'];
}
temp.word = word;
}
return root;
}
class TrieNode {
TrieNode[] next = new TrieNode[26];
String word;
}
}