题目:leetcode
Word Ladder II
Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
[ ["hit","hot","dot","dog","cog"], ["hit","hot","lot","log","cog"] ]
Note:
- All words have the same length.
- All words contain only lowercase alphabetic characters.
1、一次把同一层的单词放入visited
2、start 和 end 不在 dict 中
3、注意代码中father的设置,记录的是一个单词的“父亲们”,而不是反过来记录一个父亲的“孩子们”
4、for(auto &i:some_unordered_set) 中,i的类型是被关键字const修饰的
class Solution {
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
vector<vector<string>> res;
if(dict.empty() || start.empty() || end.empty())
{
return res;
}
unordered_set<string> cur,next,visited;
unordered_map<string,unordered_set<string>> father;//值为健的“父亲”
bool found=false;
cur.emplace(start);
while(!cur.empty() && !found)
{
for(auto &word:cur)
visited.emplace(word);
for(auto &word:cur)//这里word的类型是const string!
{
unordered_set<string> new_words=word_extend(end,word,dict,visited);
for(auto &w:new_words)
{
if(w==end)
found=true;
next.emplace(w);
father[w].emplace(word);
}
}
cur.clear();
swap(cur,next);
}
if(found)
{
vector<string> path;
gennerate_path(start,end,path,father,res);
return res;
}
else
{
return res;
}
}
unordered_set<string> word_extend(string end,string word,unordered_set<string> &dict,unordered_set<string> &visited)
{
unordered_set<string> res;
for(int i=0;i<word.size();i++)
{
char c=word[i];
for(char j='a';j<='z';j++)
{
if(j==c)
continue;
swap(word[i],j);
if( (dict.find(word)!=dict.end() || word==end) && visited.find(word)==visited.end())
res.emplace(word);
swap(word[i],j);
}
}
return res;
}
void gennerate_path(string &start, string word,vector<string> &path,unordered_map<string,unordered_set<string>> &father,vector<vector<string>> &res)
{
path.push_back(word);
if(word==start)
{
res.push_back(path);
reverse(res.back().begin(),res.back().end());
}
else
{
for(auto &i:father[word])
{
gennerate_path(start,i,path,father,res);
}
}
path.pop_back();
}
};