https://leetcode.com/problems/word-search-ii/
这道题可以用暴力搜索解决,对每一个元素进行判断。
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> res;
if(board.size()==0||board[0].size()==0) return res;
for(int i=0;i<words.size();i++){
if(find(res.begin(),res.end(),words[i])!=res.end()) continue;
if(findWord(board,words[i])) res.push_back(words[i]);
}
return res;
}
bool findWord(vector<vector<char>> &board,string &word){
vector<vector<bool>> visited(board.size(),vector<bool>(board[0].size(),false));
int i,j;
for(int i=0;i<board.size();i++){
for(int j=0;j<board[0].size();j++){
if(findRes(board,visited,i,j,word,0)) return true;
}
}
return false;
}
bool findRes(vector<vector<char>> &board,vector<vector<bool>> &visited,int line,int col,string &word,int len){
if(len==word.size()) return true;
if(col<0||line<0||col>=board[0].size()||line>=board.size()||board[line][col]!=word[len]||visited[line][col]) return false;
visited[line][col]=true;
if(findRes(board,visited,line+1,col,word,len+1)) return true;
if(findRes(board,visited,line,col+1,word,len+1)) return true;
if(findRes(board,visited,line-1,col,word,len+1)) return true;
if(findRes(board,visited,line,col-1,word,len+1)) return true;
visited[line][col]=false;
return false;
}
};
但是这个代码会TLE
作者的意图是考察字典树的应用 ,这里我们构造一个字典树,把words里的所有字符串都加到字典树里,然后用dfs搜索,如果能搜到字典树的结尾,表示已经收到了words里的字符串了,将字符串加到返回的数组里。
class TrieNode{
public:
bool end;
TrieNode* next[26];
TrieNode(){
end=false;
memset(next,0,sizeof(next));
}
};
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> res;
if(board.size()==0||board[0].size()==0) return res;
if(words.empty()) return res;
TrieNode *root=new TrieNode();
for(int i=0;i<words.size();i++) addWord(root,words[i]);
vector<vector<bool> > mark(board.size(),vector<bool>(board[0].size(),false));
string cur;
for(int i=0;i<board.size();i++){
for(int j=0;j<board[0].size();j++){
helper(res,board,mark,cur,root,i,j,board.size(),board[0].size());
}
}
return res;
}
void addWord(TrieNode* root,string &word){
TrieNode *tmp=root;
for(int i=0;i<word.size();i++){
if(tmp->next[word[i]-'a']==NULL) tmp->next[word[i]-'a']=new TrieNode();
if(i<word.size()-1) tmp=tmp->next[word[i]-'a'];
else tmp->next[word[i]-'a']->end=true;
}
}
void helper(vector<string> &ans, vector<vector<char>> &board, vector<vector<bool>> &mark, string &cur, TrieNode *p, int x, int y, int m, int n) {
if(x<0||y<0||x>=m||y>=n||mark[x][y]) return;
int pos=board[x][y]-'a';
if(!p->next[pos]) return;
else p=p->next[pos];
mark[x][y]=true;
cur.push_back(board[x][y]);
if(p->end){
ans.push_back(cur);
p->end=false;
}
helper(ans,board,mark,cur,p,x-1,y,m,n);
helper(ans,board,mark,cur,p,x+1,y,m,n);
helper(ans,board,mark,cur,p,x,y-1,m,n);
helper(ans,board,mark,cur,p,x,y+1,m,n);
cur.pop_back();
mark[x][y]=false;
}
};