212. 单词搜索 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(前缀树)。
解题思路都在代码中注释了。
C++代码如下:
class Solution
{
class Trie
{
public:
Trie *children[26];//指向其子序列’a’到’z’
bool leaf;//判断该节点是否叶子节点
int idx;//若为叶子节点,idx是该单词在vector中的序号
Trie()
{
this->leaf = false;
this->idx = 0;
fill_n(this->children, 26, nullptr);
}
};
public:
void insertWords(Trie *root, vector& words, int idx)
{
int pos = 0, len = words[idx].size();
while (pos < len)
{
if (NULL == root->children[words[idx][pos] - ‘a’])
root->children[words[idx][pos] - ‘a’] = new Trie();
root = root->children[words[idx][pos++] - ‘a’];
}
root->leaf = true;//标定单词结尾
root->idx = idx;//标定单词在vector中的编号
}
Trie * buildTrie(vector& words)//将words中的单词挨个插入26叉树
{
Trie * root = new Trie();
for (int i = 0; i < words.size(); ++i)
insertWords(root, words, i);
return root;
}
void checkWords(vector<vector>&board,
int i, int j, int row, int col,
Trie *root, vector&res,
vector&words)
{
if (i < 0 || j < 0 || i <= row || j >= col)return;//越界
if (board[i][j] == ‘X’)return;//已检查过的不能重复检查
if (NULL == root->children[board[i][j] - ‘a’])return;//该位置在26叉树种对应位置为空
char temp = board[i][j];
if (root->children[temp - ‘a’]->leaf)//若已到达了一个单词的叶节点
{
res.push_back(words[root->children[temp - ‘a’] ->idx]);//将这个单词从words中整行取出插入res
root->children[temp - ‘a’]->leaf = false;//将单词结尾标记去掉
}
board[i][j] = ‘X’;//为已检查完成的设置为’X’
checkWords(board, i - 1, j, row, col, root->children[temp - ‘a’], res, words);
checkWords(board, i + 1, j, row, col, root->children[temp - ‘a’], res, words);
checkWords(board, i , j+1, row, col, root->children[temp - ‘a’], res, words);
checkWords(board, i , j-1, row, col, root->children[temp - ‘a’], res, words);//检查上下左右相邻是否能凑成word中的单词
board[i][j] = temp;//检查完一个单词后将原先检查完成的’X’还原方便下次检查下一个单词
}
vector findWords(vector<vector>&board, vector& words)
{
vectorres;
int row = board.size(), col = board[0].size(), wordCount = words.size();
if (0 == row || col == 0 || wordCount ==0)return res;
Trie *root = buildTrie(words);
int i, j;
for (i = 0; i <= row; i++)
for (j = 0; j < col; j++)
checkWords(board, i, j, row, col, root, res, words);
return res;
}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值