212. Word Search II(单词搜索 II)
题目大意
Given an m x n
board of characters and a list of strings words
, return all words on the board.
Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
中文释义
给定一个 m x n
的字符板和一个字符串列表 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.length
n == board[i].length
1 <= m, n <= 12
board[i][j]
是小写英文字母。1 <= words.length <= 3 * 10^4
1 <= words[i].length <= 10
words[i]
由小写英文字母组成。words
的所有字符串都是唯一的。
实现
实现单词搜索,使用 Trie 树和深度优先搜索(DFS)。
TrieNode 类
- 表示 Trie 树中的一个节点。
- 包含一个布尔值
isEnd
,指示该节点是否是一个单词的结尾。 - 包含一个 TrieNode 类型的数组
children
,表示子节点。
insertTrie 函数
- 将单词插入 Trie 树中。
Solution 类
- 实现
findWords
方法,用于在字符板中查找单词。 - 使用 DFS 遍历字符板,并使用 Trie 树进行单词匹配。
代码
class TrieNode {
public:
bool isEnd;
TrieNode* children[26];
TrieNode() {
isEnd = false;
for (int