-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordSearch2.java
More file actions
71 lines (55 loc) · 1.82 KB
/
Copy pathWordSearch2.java
File metadata and controls
71 lines (55 loc) · 1.82 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
67
68
69
70
package Arrays;
import java.util.ArrayList;
import java.util.List;
/*
https://leetcode.com/problems/word-search-ii/discuss/59780/Java-15ms-Easiest-Solution-(100.00)
*/
public class WordSearch2 {
static class TrieNode {
String word;
TrieNode[] children;
TrieNode() {
children = new TrieNode[26];
}
}
public List<String> searchWords(char[][] board, List<String> words) {
List<String> result = new ArrayList<>();
TrieNode root = new TrieNode();
buildTrie(words, root);
for (var i = 0; i < board.length; i++) {
for (var j = 0; j < board[0].length; j++) {
dfs(board, root, result, i, j);
}
}
return result;
}
private void buildTrie(List<String> words, TrieNode root) {
for (String str : words) {
TrieNode cur = root;
for (var ch : str.toCharArray()) {
int pos = ch - 'a';
if (cur.children[pos] == null)
cur.children[pos] = new TrieNode();
cur = cur.children[pos];
}
cur.word = str;
}
}
private void dfs(char[][] board, TrieNode root, List<String> result, int x, int y) {
char ch = board[x][y];
if (ch == '#' || root.children[ch - 'a'] == null)
return;
root = root.children[ch - 'a'];
if (root.word != null) {
result.add(root.word);
root.word = null;
return;
}
board[x][y] = '#';
if (x > 0) dfs(board, root, result, x - 1, y);
if (y > 0) dfs(board, root,result, x, y - 1);
if (x < board.length - 1) dfs(board, root, result, x+1, y);
if (y < board[0].length) dfs(board, root, result, x, y + 1);
board[x][y] = ch;
}
}