-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0212-word-search-ii.java
100 lines (88 loc) · 2.85 KB
/
0212-word-search-ii.java
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
class Solution {
private static int COLS;
private static int ROWS;
private Trie currentTrie;
public List<String> findWords(char[][] board, String[] words) {
Trie root = new Trie();
for (String word : words) {
root.addWord(word);
}
ROWS = board.length;
COLS = board[0].length;
HashSet<String> res = new HashSet<>();
HashSet<String> visit = new HashSet<>();
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLS; c++) {
dfs(r, c, root, "", res, visit, board, root);
}
}
return new ArrayList<>(res);
}
public void dfs(
int r,
int c,
Trie node,
String word,
HashSet<String> res,
HashSet<String> visit,
char[][] board,
Trie root
) {
if (
r < 0 ||
c < 0 ||
r == ROWS ||
c == COLS ||
!node.children.containsKey(board[r][c]) ||
node.children.get(board[r][c]).refs < 1 ||
visit.contains(r + "-" + c)
) {
return;
}
visit.add(r + "-" + c);
node = node.children.get(board[r][c]);
word += board[r][c];
if (node.isWord) {
node.isWord = false;
res.add(word);
root.removeWord(word);
}
dfs(r + 1, c, node, word, res, visit, board, root);
dfs(r - 1, c, node, word, res, visit, board, root);
dfs(r, c + 1, node, word, res, visit, board, root);
dfs(r, c - 1, node, word, res, visit, board, root);
visit.remove(r + "-" + c);
}
class Trie {
public HashMap<Character, Trie> children;
public boolean isWord;
public int refs = 0;
public Trie() {
children = new HashMap<>();
}
public void addWord(String word) {
currentTrie = this;
currentTrie.refs += 1;
for (int i = 0; i < word.length(); i++) {
char currentCharacter = word.charAt(i);
if (!currentTrie.children.containsKey(currentCharacter)) {
currentTrie.children.put(currentCharacter, new Trie());
}
currentTrie = currentTrie.children.get(currentCharacter);
currentTrie.refs += 1;
}
currentTrie.isWord = true;
}
public void removeWord(String word) {
currentTrie = this;
currentTrie.refs -= 1;
for (int i = 0; i < word.length(); i++) {
char currentCharacter = word.charAt(i);
if (currentTrie.children.containsKey(currentCharacter)) {
currentTrie = currentTrie.children.get(currentCharacter);
currentTrie.refs -= 1;
}
}
}
}
}