/*BFS算法。此题与Word Ladder类似,但是需要记录路径。需要解决额外两个问题:
1.不能在遍历到当前单词时,删掉遍历到的单词,因为上一层中还未遍历的单词可能能到这个单词,所以只能记下来,
等到遍历完当前层时,统一删除。
2.为了能够获得路径,需要记录每个单词的前一个单词。
参考自:https://github.com/soulmachine/leetcode*/
class Solution {
public:
vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) {
queue<string> cur, next;
unordered_map<string, vector<string> > parents;
unordered_set<string> hash;
bool isfound(false);
cur.push(start);
while(!cur.empty()){
while(!cur.empty()){
string str = cur.front(), strcpy(str);
cur.pop();
for(int i = 0; i < str.size(); ++i){
for(char c = 'a'; c < 'z'+1; ++c){
if(c == str[i]) continue;
str[i] = c;
if(str == end){
parents[end].push_back(strcpy);
isfound = true;
break;
}
else{
if(dict.find(str) != dict.end() && !isfound){
if(hash.find(str) == hash.end()){
next.push(str);
hash.insert(str);
}
parents[str].push_back(strcpy);
}
}
}
str[i] = strcpy[i];
}
}
if(isfound) break;
else{
swap(cur, next);
for(unordered_set<string>::iterator it = hash.begin(); it != hash.end(); ++it){
dict.erase(*it);
}
hash.clear();
}
}
vector<vector<string> > res;
if(parents.find(end) == parents.end()) return res;
vector<string> path;
getLadders(res, parents, path, start, end);
return res;
}
void getLadders(vector<vector<string> > &res, unordered_map<string, vector<string> > &parents,
vector<string> &path, string &start, string cur){
if(cur == start){
path.push_back(start);
reverse(path.begin(), path.end());
res.push_back(path);
reverse(path.begin(), path.end());
path.pop_back();
return;
}
path.push_back(cur);
for(int i = 0; i < parents[cur].size(); ++i){
getLadders(res, parents, path, start, parents[cur][i]);
}
path.pop_back();
}
};
LeetCode之Word Ladder II
最新推荐文章于 2020-04-18 01:25:00 发布