题目地址:点击打开链接
class Solution {
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
unordered_set<string> current,next,visited;
current.insert(start);
bool isFound=false;
while(!current.empty()&&!isFound) {
for(unordered_set<string>::iterator it=current.begin();it!=current.end();++it)visited.insert(*it);
for(unordered_set<string>::iterator it=current.begin();it!=current.end();++it){
for(int i=0;i<start.size();++i) {
for(int j=0;j<26;++j) {
string temp=*it;
temp[i]=j+'a';
if(temp!=*it&&dict.count(temp)>0&&visited.count(temp)==0){
father[temp].push_back(*it);
next.insert(temp);
if(temp==end)isFound=true;
}
}
}
}
current=next;
next.clear();
}
if(!isFound)return vvs;
dfs(start,end,vector<string>(1,end));
return vvs;
}
private:
vector<vector<string>> vvs;
unordered_map<string,vector<string>> father;
void dfs(string start,string end,vector<string> vs){
if(end==start){
vvs.push_back(vs);
return;
}
for(int i=0;i<father[end].size();++i){
vector<string> temp=vs;
temp.insert(temp.begin(),father[end][i]);
dfs(start,father[end][i],temp);
}
}
};