Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input: words =["oath","pea","eat","rain"]
and board = [ ['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v'] ] Output:["eat","oath"]
题解:主框架同之前的word search直接回溯,但是如果对每一个字符串都进行回溯会超时,此时需要只遍历一次图然后每个点回溯过程中便把words里的字符串全部搜索,这里需要用tire的数据结构,利用字典树,相当于之前只是遍历一个word现在遍历一棵树,遍历树的过程遇到单词则加入ans,这里遇到了很难发现的bug主要对回溯法没理解清楚,首先我传入一个string tmp,如果用引用类型在回溯返回的过程中如果没有pop会一直加下去
代码:
class TrieNode {
public:
// Initialize your data structure here.
TrieNode *child[26];
bool isWord;
TrieNode() : isWord(false){
for (auto &a : child) a = NULL;
}
};
class Trie {
public:
TrieNode* root;
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string s) {
TrieNode *p = root;
for (auto &a : s) {
int i = a - 'a';
if (!p->child[i]) p->child[i] = new TrieNode();
p = p->child[i];
}
p->isWord = true;
}
};
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
Trie* trie=new Trie();
for(auto& w:words){
trie->insert(w);
}
TrieNode* root=trie->root;
vector<string> ans;
for(int i=0;i<board.size();i++){
for(int j=0;j<board[0].size();j++){
string tmp;
dfs(root,board,ans,tmp,i,j);
}
}
return ans;
}
void dfs(TrieNode* root,vector<vector<char>>& G,vector<string>& ans,string& tmp,int i,int j){
if(i<0||j<0||i>=G.size()||j>=G[0].size()||G[i][j]=='*') return;
char c=G[i][j];
if(root->child[c-'a']){
root=root->child[c-'a'];
}else return;
tmp+=G[i][j];
if(root->isWord) {
ans.push_back(tmp);root->isWord=false;
}
G[i][j]='*';
dfs(root,G,ans,tmp,i+1,j);
dfs(root,G,ans,tmp,i-1,j);
dfs(root,G,ans,tmp,i,j+1);
dfs(root,G,ans,tmp,i,j-1);
G[i][j]=c;
tmp.pop_back();
}
};