字典树+回溯
使用unordered_map去重
class Solution {
public:
int tree[10000][30],ed[10000],tot,vis[15][15],n,m;
vector<string>res;
unordered_map<int,string>mp;
unordered_map<int,int>mp2;
void insert(string s){
int root=0;
for(auto tmp:s){
if(tree[root][tmp-'a']==0)
tree[root][tmp-'a']=++tot;
root=tree[root][tmp-'a'];
}
ed[root]=1;
mp[root]=s;
}
vector<pair<int,int>>pa={{1,0},{-1,0},{0,1},{0,-1}};
void dfs(int root,int x,int y,vector<vector<char>>& board){
//cout<<root<< x<< y<<endl;
vis[x][y]=1;
root=tree[root][board[x][y]-'a'];
if(ed[root]==1 && mp2[root]==0)
res.push_back(mp[root]),mp2[root]=1;
//cout<<root<<endl;
for(auto tmp:pa){
int tox=tmp.first+x;
int toy=tmp.second+y;
//cout<<tox<<toy<<endl;
if(tox>=0 && tox<n && toy<m && toy>=0 && vis[tox][toy]==0 && tree[root][board[tox][toy]-'a']) {
//cout<<tox<<toy<<endl;
dfs(root,tox,toy,board);
}
//cout<<10086<<endl;
}
vis[x][y]=0;
}
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
memset(tree,0,sizeof(tree));
memset(ed,0,sizeof(ed));
memset(vis,0,sizeof(vis));
tot=0;
m=board[0].size();
n=board.size();
for(auto i:words)
insert(i);
for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
if(tree[0][board[i][j]-'a'])
dfs(0,i,j,board);
}
}
return res;
}
};