本题源自LeetCode
———————————————————————————-
大神的想法
http://www.cnblogs.com/ShaneZhang/p/3748494.html
=——————————————————————————————–
vector<vector<string>> result;
vector<string> temp;
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
temp.clear();
result.clear();
unordered_set<string> current;
unordered_set<string> next;
unordered_map<string,unordered_set<string>> path;
unordered_set<string> ret=dict;
//从字典中删除单词
if(ret.count(start)>0)
ret.erase(start);
current.insert(start);
while(current.count(end)==0&&ret.size()>0){
for(auto p=current.begin();p!=current.end();p++){
string word=*p;
for(int i=0;i<start.length();i++){
for(char j='a';j<='z';j++){
string tmp=word;
if(tmp[i]==j)
continue;
tmp[i]=j;
if(ret.count(tmp)>0){
next.insert(tmp);
//构建反向邻接链表
path[tmp].insert(word);
}
}
}
}
if(next.empty())
break;
//从字典中删除这个层的单词避免重复
for(auto p=next.begin();p!=next.end();p++){
ret.erase(*p);
}
current=next;
next.clear();
}
if(current.count(end)>0)
GeneratePath(end,start,path);
return result;
}
void GeneratePath(string& start,string& end,unordered_map<string,unordered_set<string>>& path){
temp.push_back(start);
if(start==end){
reverse(temp.begin(),temp.end());
result.push_back(temp);
reverse(temp.begin(),temp.end());
return;
}
for(auto it = path[start].begin(); it != path[start].end(); ++it){
string str=*it;
GeneratePath(str, end, path);
temp.pop_back();
}
}