一、题目介绍
给定一个二维网格 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 组成。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
二、解题思路
遍历二维网格,以每一个元素作为起点,按照可行路线确定单词列表中是否有当前字符串。因为每个位置有上、下、左、右四个方向可以移动,所以采用回溯算法,为了减少递归次数走过的路径需要记录,走完之后再恢复现场。
查找某一字符是否包含于单词列表中,使用前缀树来完成,可以在O(n)时间复杂度内完成查找。
三、解题代码
struct Node
{
bool word;
string str;
unordered_map<char, Node*> mp;
};
class Trie
{
private:
Node* root;
public:
Trie()
{
root = new Node();
}
void insert(string word)
{
Node* p = root;
for(auto c:word)
{
if(p->mp.find(c) == p->mp.end())
{
p->mp[c] = new Node();
}
p = p->mp[c];
}
p->word = true;
p->str = word;
}
void search(vector<string>& res, vector<vector<char>>& board)
{
for(int i = 0; i < board.size(); ++i)
{
for(int j = 0; j < board[0].size(); ++j)
{
helper(res, board, root, i, j); //以每一个表格中的元素为起点进行查找
}
}
}
void helper(vector<string>& res, vector<vector<char>>& board, Node* p, int x, int y)
{
if(p->word)
{
res.push_back(p->str);
p->word = false; // 防止没有进行比较直接保存
return;
}
if(x < 0 || x == board.size() || y < 0 || y == board[0].size())
return;
if(p->mp.find(board[x][y]) == p->mp.end())
return;
p = p->mp[board[x][y]];
char cur = board[x][y];
board[x][y] = '#'; // 标记走过的路径
helper(res, board, p, x+1, y);
helper(res, board, p, x-1, y);
helper(res, board, p, x, y+1);
helper(res, board, p, x, y-1);
board[x][y] = cur; // 恢复现场
}
};
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
Trie t;
for(auto s:words)
{
t.insert(s);
}
vector<string> res;
t.search(res, board);
return res;
}
};