LeetCode之Word Ladder II

/*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();
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值