题目链接:https://leetcode-cn.com/problems/word-search-ii/
题目描述
给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母在一个单词中不允许被重复使用。
示例:
输入:
words = ["oath","pea","eat","rain"] and board =
[
['o','a','a','n'],
['e','t','a','e'],
['i','h','k','r'],
['i','f','l','v']
]
输出: ["eat","oath"]
说明:
你可以假设所有输入都由小写字母 a-z 组成。
提示:
- 你需要优化回溯算法以通过更大数据量的测试。你能否早点停止回溯?
- 如果当前单词不存在于所有单词的前缀中,则可以立即停止回溯。什么样的数据结构可以有效地执行这样的操作?散列表是否可行?为什么? 前缀树如何?如果你想学习如何实现一个基本的前缀树,请先查看这个问题: 实现Trie(前缀树)。
思路
该题如果没有提示的话,使用DFS搜索+遍历词典也可以做,但是复杂度必然非常高。
主要步骤如下:
(1)建立前缀树
(2)遍历board上的每个元素,以其作为起始节点,进行DFS,记录当前的路径
(3)如果当前的格子的字符在前缀树中对应路径上,则继续遍历旁边的格子,同时将该格元素标记为’#’,代表已经走过;
如果当前前缀树节点是一个终止节点(即该路径代表了一个词),则表示找到,将路径记录下来。
(4)继续(2)~(3)
本人一开始直接记录当前path,并调用前缀树的startsWith和search方法去判断path是否在词典内,这样每次判断都需要从前缀树的root开始遍历,重复操作多,非常低效。虽然提交通过,但是耗时~176ms,仅超过44%。并且一开始采用一个数组visited来记录当前路径是否走过,后来观察到输入的board范围是确定的,可以通过更改board的字符来标志,可以省去额外数组的内存开销。
下面是实现的一些具体细节:
- 每次取当前进入的格子的字符ch,当前走到的前缀树的ch子节点是否存在;避免从前缀树的根开始遍历
- 如果当前子节点是一个终止节点,则记录下当前路径
- 因为可能有重复的路径,所以在遍历的时候是用map来记录,最后再转为vector返回即可
- 注意:在DFS的过程中,最后要恢复当前格子的字符
代码
class Trie {
public:
Trie* next[26] = {};
bool isEnd= false; // 表明是否是单词结尾
/** Initialize your data structure here. */
Trie() {}
/** Inserts a word into the trie. */
void insert(string word) {
Trie* node = this;
for(char ch:word){
ch -= 'a'; // 得到字符的序号
if(!node->next[ch]){
// 若当前字符不存在 创建新节点
node->next[ch] = new Trie();
}
node = node->next[ch];
}
node->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* node = this;
for(char ch: word){
ch-= 'a';
if(!node->next[ch]) // 如果不匹配
return false;
node = node->next[ch];
}
return node->isEnd; // 只有当遍历到词的结尾时才成功
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie* node = this;
for (char ch:prefix){
ch -= 'a';
if(!node->next[ch])
return false;
node = node->next[ch];
}
return true; // 前缀遍历结束则成功
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
if(board.empty() || words.empty())
return vector<string> {};
Trie *obj = new Trie();
for (string w:words)
obj->insert(w);
vector<string> ret;
unordered_set<string> result_set;
vector<vector<bool>> visited(board.size(), vector<bool> (board[0].size(), false));
string path; // 当前序列
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[0].size(); ++j) {
findWordsCore(board, i, j, path, obj, result_set);
}
}
for (auto it:result_set)
ret.push_back(it);
return ret;
}
void findWordsCore(vector<vector<char>>& board, int row, int col, string &path, Trie *obj, unordered_set<string> &ret){
if(row>=0 && row<board.size() && col>=0 && col<board[0].size() && board[row][col]!='#' ){
char ch = board[row][col];
char chIndex = ch - 'a';
// 如果当前单词不存在于所有单词的前缀中,则可以立即停止回溯
if(obj->next[chIndex]){
path.push_back(ch);
obj = obj->next[chIndex]; // 需要前进到子节点
board[row][col] = '#';
if(obj->isEnd)
ret.insert(path);
findWordsCore(board, row-1, col, path, obj, ret);
findWordsCore(board, row+1, col, path, obj, ret);
findWordsCore(board, row, col-1, path, obj, ret);
findWordsCore(board, row, col+1, path, obj, ret);
// 恢复
board[row][col] = ch;
path.pop_back();
}
}
}
};