Repository navigation
Expand file tree
/
Copy pathSolution.java
More file actions
79 lines (63 loc) · 1.78 KB
/
Copy pathSolution.java
File metadata and controls
79 lines (63 loc) · 1.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
package com.yeahqing.hard._212;
import java.util.*;
/**
* @author YeahQing
* @date 2022/10/25
* leetcode-212 单词搜索 II
* 回溯法+前缀树
*/
public class Solution {
int[][] dirs = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public List<String> findWords(char[][] board, String[] words) {
Trie trie = new Trie();
for (String word : words) {
trie.insert(word);
}
Set<String> ans = new HashSet<>();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
dfs(board, trie, i, j, ans);
}
}
return new ArrayList<String>(ans);
}
public void dfs(char[][] board, Trie now, int i, int j, Set<String> ans) {
if (!now.children.containsKey(board[i][j])) {
return;
}
char ch = board[i][j];
board[i][j] = '#';
now = now.children.get(ch);
if (now.isWord) {
ans.add(now.word);
}
for (int[] dir : dirs) {
int i1 = i + dir[0], j1 = j + dir[1];
if (i1 >= 0 && i1 < board.length && j1 >= 0 && j1 < board[0].length) {
dfs(board, now, i1, j1, ans);
}
}
board[i][j] = ch;
}
}
class Trie {
String word;
Map<Character, Trie> children;
boolean isWord;
public Trie() {
word = "";
children = new HashMap<>();
isWord = false;
}
public void insert(String word) {
Trie cur = this;
for (Character c : word.toCharArray()) {
if (!cur.children.containsKey(c)) {
cur.children.put(c, new Trie());
}
cur = cur.children.get(c);
}
cur.isWord = true;
cur.word = word;
}
}