212. 单词搜索II
题目
描述:
给定一个 m x n 二维字符网格 board 和一个单词(字符串)列表 words,返回所有二维网格上的单词。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例 1:
- 输入:
board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]],words = ["oath","pea","eat","rain"] - 输出:
["eat","oath"]
示例 2:
- 输入:
board = [["a","b"],["c","d"]],words = ["abcb"] - 输出:
[]
提示:
m == board.lengthn == board[i].length1 <= m, n <= 12board[i][j]是一个小写英文字母1 <= words.length <= 3 * 10^41 <= words[i].length <= 10words[i]由小写英文字母组成words中的所有字符串互不相同
题解
将所有目标词放进同一棵 Trie
逐个搜索单词会反复走过共享前缀。例如目标中有 eat、ear,匹配前两个字符的过程可以共用。先把所有词插入 Trie,终点的 word 保存完整单词,其他节点的 word 为 null。
从棋盘每个格子出发 DFS,同时沿 Trie 的字符分支前进。棋盘决定哪些格子相邻,Trie 判断已形成的前缀是否还可能匹配目标。缺少对应分支时立即返回,无须继续搜索更长路径。
棋盘位置和 Trie 节点同步前进
进入 dfs(board, i, j, node, res) 时,node 对应此前已经匹配的前缀,当前格子的字符尚未加入。先检查坐标、访问标记,再查找当前字符的孩子;存在时进入该孩子,并检查是否到达单词终点。
找到单词后加入答案,再将 node.word 置空,防止其他棋盘路径重复输出同一个词。但不能直接返回,因为当前单词也可能是更长目标词的前缀,仍要继续探索孩子。清空 word 不会删除字符分支。
标记与恢复只限制当前路径
将当前格子暂存为字符 c,改成 '#',再递归上下左右。这样同一路径不能重复使用这个格子;四个方向全部处理完后恢复 c,让其他起点和分支仍可使用它。标记检查要先于 c - 'a',避免把 '#' 当成字母下标。
例如路径 e → a → t 命中 eat 后,即使另一条路径再次拼出 eat,结束标记已清空,不会重复加入。一次 findWords 会重新构造 Trie,且搜索返回前恢复棋盘,之后再次调用仍可独立工作。
复杂度
设棋盘为 $m×n$,所有目标词字符总数为 $K$,最长词长为 $L$,令 $D = \min(L,mn)$。建 Trie 需 $O(K)$;每个起点首个扩展最多有 4 个方向,之后由于不能立即走回前一格,分支至多为 3,保守总时间上界为 $O(K+mn×3^D)$。前缀不存在时会提前剪枝,实际搜索通常更少。
不计结果列表,Trie 占 $O(K)$,回溯栈占 $O(D)$。字符在棋盘上原地标记,不另建访问矩阵。
完整示例
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
import java.util.ArrayList;
import java.util.List;
public class Main {
static class Solution {
class TrieNode {
String word;
TrieNode[] children = new TrieNode[26];
}
private TrieNode buildTrie(String[] words) {
TrieNode root = new TrieNode();
for (String w : words) {
TrieNode node = root;
for (char c : w.toCharArray()) {
int idx = c - 'a';
if (node.children[idx] == null) {
node.children[idx] = new TrieNode();
}
node = node.children[idx];
}
node.word = w;
}
return root;
}
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;
}
private void dfs(char[][] board, int i, int j, TrieNode node, List<String> res) {
if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] == '#') {
return;
}
char c = board[i][j];
int idx = c - 'a';
if (node.children[idx] == null) {
return;
}
node = node.children[idx];
if (node.word != null) {
res.add(node.word);
node.word = null;
}
board[i][j] = '#';
dfs(board, i + 1, j, node, res);
dfs(board, i - 1, j, node, res);
dfs(board, i, j + 1, node, res);
dfs(board, i, j - 1, node, res);
board[i][j] = c;
}
}
public static void main(String[] args) {
Solution solution = new Solution();
char[][] board1 = {
{'o', 'a', 'a', 'n'},
{'e', 't', 'a', 'e'},
{'i', 'h', 'k', 'r'},
{'i', 'f', 'l', 'v'}
};
String[] words1 = {"oath", "pea", "eat", "rain"};
System.out.println("示例 1 输出: " + solution.findWords(board1, words1));
char[][] board2 = {
{'a', 'b'},
{'c', 'd'}
};
String[] words2 = {"abcb"};
System.out.println("示例 2 输出: " + solution.findWords(board2, words2));
char[][] board3 = {
{'a', 'p', 'p'},
{'p', 'l', 'e'}
};
String[] words3 = {"app", "apple"};
System.out.println("示例 3 输出: " + solution.findWords(board3, words3));
}
}
运行结果(OpenJDK 21.0.12):
1
2
3
示例 1 输出: [oath, eat]
示例 2 输出: []
示例 3 输出: [app]
题目不要求返回顺序,这里的顺序取决于在网格上找到单词的先后,与题面示例的 ["eat","oath"] 等价。


