-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay16.java
More file actions
73 lines (61 loc) · 2.15 KB
/
Day16.java
File metadata and controls
73 lines (61 loc) · 2.15 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
71
72
73
import java.util.ArrayList;
import java.util.List;
class TrieNode {
TrieNode[] children = new TrieNode[26];
String word;
}
public class Day16 {
private void insertWord(TrieNode root, String word) {
TrieNode node = root;
for (char ch : word.toCharArray()) {
int index = ch - 'a';
if (node.children[index] == null) {
node.children[index] = new TrieNode();
}
node = node.children[index];
}
node.word = word;
}
private void search(char[][] board, int i, int j, TrieNode node, List<String> result) {
char ch = board[i][j];
if (ch == '#' || node.children[ch - 'a'] == null) {
return;
}
node = node.children[ch - 'a'];
if (node.word != null) {
result.add(node.word);
node.word = null;
}
board[i][j] = '#';
if (i > 0) search(board, i - 1, j, node, result);
if (i < board.length - 1) search(board, i + 1, j, node, result);
if (j > 0) search(board, i, j - 1, node, result);
if (j < board[0].length - 1) search(board, i, j + 1, node, result);
board[i][j] = ch;
}
public List<String> findWords(char[][] board, String[] words) {
TrieNode root = new TrieNode();
for (String word : words) {
insertWord(root, word);
}
List<String> result = new ArrayList<>();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
search(board, i, j, root, result);
}
}
return result;
}
public static void main(String[] args) {
Day16 wordSearchII = new Day16();
char[][] board = {
{'o', 'a', 'a', 'n'},
{'e', 't', 'a', 'e'},
{'i', 'h', 'k', 'r'},
{'i', 'f', 'l', 'v'}
};
String[] words = {"oath", "pea", "eat", "rain"};
List<String> result = wordSearchII.findWords(board, words);
System.out.println("Words found on the board: " + result);
}
}