class Solution {
public:
void generatepath(unordered_map<string,vector<string>>&father,string start,string word,vector<string> &path,vector<vector<string>>&result)
{
path.push_back(word);
if(word==start)
{
result.push_back(path);
reverse(result.back().begin(),result.back().end());
}
else
{
for(auto f:father[word])
generatepath(father,start,f,path,result);
}
path.pop_back();
}
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
unordered_set<string> current,next;
unordered_map<string,vector<string>> father;
unordered_set<string> visited;
bool found=false;
current.insert(start);
while(!current.empty()&&!found)
{
for(auto iter=current.begin();iter!=current.end();iter++)
{
visited.insert(*iter);
}
for(auto iter=current.begin();iter!=current.end();iter++)
{
for(int i=0;i<iter->size();i++)
{
string word=*iter;
for(char c='a';c<='z';c++)
{
if(c==word[i])
continue;
swap(c,word[i]);
if(word==end)
found=true;
if(visited.count(word)==0&&dict.count(word)>0||word==end)
{
father[word].push_back(*iter);
next.insert(word);
}
swap(c,word[i]);
}
}
}
current.clear();
swap(next,current);
}
vector<vector<string>> result;
if(found)
{
vector<string> path;
generatepath(father,start,end,path,result);
}
return result;
}
};
public:
void generatepath(unordered_map<string,vector<string>>&father,string start,string word,vector<string> &path,vector<vector<string>>&result)
{
path.push_back(word);
if(word==start)
{
result.push_back(path);
reverse(result.back().begin(),result.back().end());
}
else
{
for(auto f:father[word])
generatepath(father,start,f,path,result);
}
path.pop_back();
}
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
unordered_set<string> current,next;
unordered_map<string,vector<string>> father;
unordered_set<string> visited;
bool found=false;
current.insert(start);
while(!current.empty()&&!found)
{
for(auto iter=current.begin();iter!=current.end();iter++)
{
visited.insert(*iter);
}
for(auto iter=current.begin();iter!=current.end();iter++)
{
for(int i=0;i<iter->size();i++)
{
string word=*iter;
for(char c='a';c<='z';c++)
{
if(c==word[i])
continue;
swap(c,word[i]);
if(word==end)
found=true;
if(visited.count(word)==0&&dict.count(word)>0||word==end)
{
father[word].push_back(*iter);
next.insert(word);
}
swap(c,word[i]);
}
}
}
current.clear();
swap(next,current);
}
vector<vector<string>> result;
if(found)
{
vector<string> path;
generatepath(father,start,end,path,result);
}
return result;
}
};