/**********************************************************************************************************
9.2 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 leer 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.
分析
跟 Word Ladder 比,这题是求路径本身,不是路径长度,也是 BFS,略微麻烦点。
这题跟普通的广搜有很大的不同,就是要输出所有路径,因此在记录前驱和判重地方与普广搜略有不同
**********************************************************************************************************/
class Solution{
public:
vector<vector<sting>> findLadders(string start, string end,const unordered_set<string> &dict){
unorder_set<string> visited; //判重
unorder_map<string, vector<string>> father;
unorder_set<string> current, next;
bool found = false;
current.insert(start);
while(!current.empty() && !found){
for(auto word : current){
visited.insert(word); //先将本层全部置为已访问,防止同层之间互相指向
}
for(auto word : current){
for(size_t i = 0; i < word.size(); i ++){
string new_word = word;
for(char c = 'a';c < 'z';c ++){
if(c == new_word[i]) contuine;
swap(c, new_word[i]);
if(new_word == end()) found = true;
if(visited.count(new_word) == 0 && (dict.count(new_word)> 0)||
new_word == end){
next.insert(new_word);
father[new_word].push_back(word);
}
swap(c ,new_word[i]);//restore
}
}
}
current.clear();
swap(current, next);
}
vector<vector<string>> result;
if(found){
vector<string> path;
bulidPath(father, path, start, end , result);
}
return result;
}
private:
void bulidPath(unordered_map<string, vector<string>> &father,vecotr<string> &path,const string &start,
const string &end , 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]){
bulidPath(father, path, f, result);
}
}
path.pop_back();
}
};
参考资料:
LeetCode题解