forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindWords.java
More file actions
63 lines (57 loc) · 1.84 KB
/
FindWords.java
File metadata and controls
63 lines (57 loc) · 1.84 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
package tree;
import java.util.ArrayList;
import java.util.List;
public class FindWords {
public List<String> findWords(char[][] board, String[] words){
List<String> res = 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,res);
}
}
return res;
}
public void dfs(char[][] board, int i, int j,TrieNode p,List<String> res){
char c = board[i][j];
if (c == '#' || p.next[c-'a'] == null) return;
p = p.next[c-'a'];
if (p.word != null){
res.add(p.word);
p.word = null;
}
board[i][j] = '#';
if (i>0) dfs(board,i-1,j,p,res);
if (j>0) dfs(board,i,j-1,p,res);
if (i<board.length-1) dfs(board,i+1,j,p,res);
if (j<board[0].length -1) dfs(board,i,j+1,p,res);
board[i][j] = c;
}
public TrieNode buildTrie(String[] words){
TrieNode root = new TrieNode();
for (String w : words){
TrieNode p = root;
for (char c : w.toCharArray()){
int i = c - 'a';
if (p.next[i] == null) p.next[i] = new TrieNode();
p = p.next[i];
}
p.word = w;
}
return root;
}
class TrieNode{
TrieNode[] next = new TrieNode[26];
String word;
}
public static void main(String[] args) {
char[][] board ={{'o','a','a','n'},
{'e','t','a','e'},
{'i','h','k','r'},
{'i','f','l','v'}};
String[] words = {"oath","pea","eat","rain"};
FindWords findWords = new FindWords();
List<String> r = findWords.findWords(board,words);
System.out.println(r.toString());
}
}