-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordSearchII.java
108 lines (80 loc) · 2.87 KB
/
WordSearchII.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
101
102
103
104
105
106
107
108
/*
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring.
The same letter cell may not be used more than once in a word.
Example:
Input:
board = [
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
Note:
All inputs are consist of lowercase letters a-z.
The values of words are distinct.
*/
class TrieNode{
TrieNode[] children;
String word;
TrieNode(){
children = new TrieNode[26];
for(int i=0; i<26; i++){
children[i] = null;
}
}
}
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++){
DFS(board,i,j,root,result);
}
}
return result;
}
private void DFS(char[][] board,int i,int j,TrieNode root,List<String> result){
char c = board[i][j];
//check if this cell is already visired or then there is no word starting at from this root of Trie Tree
if(c == '*' || root.children[c - 'a'] == null){
return;
}
//make child as root
root = root.children[c - 'a'];
//if we have found any word then add it to the list and also make it null so its not added again
if(root.word != null){
result.add(root.word);
root.word = null;
}
//Mark it as '*' so its not visited again
board[i][j] = '*';
if(i > 0) DFS(board,i-1,j,root,result);
if(j > 0) DFS(board,i,j-1,root,result);
if(i < board.length - 1) DFS(board,i+1,j,root,result);
if(j < board[0].length -1) DFS(board,i,j+1,root,result);
//After backtracking change it to original character
board[i][j] = c;
}
private TrieNode buildTrie(String[] words){
TrieNode root = new TrieNode();
for(int i=0; i<words.length; i++){
String s = words[i];
TrieNode curr = root;
for(int j=0; j<s.length(); j++){
if(curr.children[s.charAt(j) - 'a'] == null){
curr.children[s.charAt(j) - 'a'] = new TrieNode();
curr = curr.children[s.charAt(j) - 'a'];
}
else{
curr = curr.children[s.charAt(j) - 'a'];
}
}
curr.word = s;
}
return root;
}
}