-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordSearchII.java
More file actions
92 lines (78 loc) · 2.78 KB
/
Copy pathWordSearchII.java
File metadata and controls
92 lines (78 loc) · 2.78 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.*;
class WordSearchII {
private class TrieNode {
TrieNode[] children = new TrieNode[26];
String word = null;
}
private TrieNode root;
public List<String> findWords(char[][] board, String[] words) {
List<String> result = new ArrayList<>();
if (board == null || board.length == 0 || board[0].length == 0 || words == null || words.length == 0) {
return result;
}
// Build the Trie
root = new TrieNode();
for (String word : words) {
insert(word);
}
// Start DFS from each cell
int rows = board.length;
int cols = board[0].length;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
if (root.children[board[row][col] - 'a'] != null) {
dfs(board, row, col, root, result);
}
}
}
return result;
}
private void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
node.children[index] = new TrieNode();
}
node = node.children[index];
}
node.word = word;
}
private void dfs(char[][] board, int row, int col, TrieNode node, List<String> result) {
char c = board[row][col];
if (c == '#' || node.children[c - 'a'] == null) {
return;
}
node = node.children[c - 'a'];
if (node.word != null) {
result.add(node.word);
node.word = null; // Avoid duplicate entries
}
// Mark the cell as visited
board[row][col] = '#';
int[][] directions = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
for (int[] direction : directions) {
int newRow = row + direction[0];
int newCol = col + direction[1];
if (newRow >= 0 && newRow < board.length && newCol >= 0 && newCol < board[0].length) {
dfs(board, newRow, newCol, node, result);
}
}
// Restore the cell
board[row][col] = c;
}
public static void main(String[] args) {
WordSearchIIPart2 solution = new WordSearchIIPart2();
char[][] board = {
{'o','a','a','n'},
{'e','t','a','e'},
{'i','h','k','r'},
{'i','f','l','v'}
};
String[] words = {"oath", "pea", "eat", "rain"};
System.out.println(solution.findWords(board, words)); // Output: [oath, eat]
char[][] board1 = {{'a','b'},{'c','d'}};
String[] words1 = {"abcb", "bd"};
System.out.println(solution.findWords(board1, words1)); // Output: []
}
}