leetcode 126 Word Ladder II

参考:https://www.cnblogs.com/grandyang/p/4548184.html

基本思想是广度优先搜索,level表示当前已经放到路径中的word总数;每一次while循环,将当前这条路径(当前这个vector<string>)的下一个word的所有情况放入队列中,直到遇到了endWord;遇到了endWord,说明这一层(这个level)就是路径最短的一层,到了下一层(t.size()>level,实际上t.size()=level+1)时,保存的结果vector<vector<string>> 不为空,就可以停止搜索。

class Solution {
public:
    vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> dict(wordList.begin(),wordList.end()),words; //dict为所有wordList,set搜索更快;words为已经添加到路径中的word
        queue<vector<string>> q;
        vector<vector<string>> re;
        vector<string> vec{beginWord};
        q.push(vec);
        int level=1;//当前队列q中的vector<string>的大小
        while(!q.emtpy()) {
            auto t=q.front();q.pop();
            if(t.size()>level) {
                for(auto& word:words) dict.erase(word);
                words.clear();
                level=t.size();
                if(!re.empty()) break;
            }
            string Last=t.back();//back()返回的是引用
            for(int i=0;i<Last.size();++i) {
                string newLast=Last;
                for(char ch='a';ch<='z';++ch) {
                    newLast[i]=ch;
                    if(!dict.count(newLast)) continue;
                    t.push_back(newLast);
                    words.insert(newLast);
                    if(newLast==endWord) {
                        re.push_back(t);
                    }
                    else q.push(t);
                    t.pop_back();
                }
            }
        }
        return re;
    }
};

 

posted @ 2020-03-17 16:25  qiujiejie  阅读(180)  评论(0)    收藏  举报