126. Word Ladder II

class Solution {
public:
    vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> s(wordList.begin(), wordList.end());
        vector<vector<string>> res;
        if (s.find(endWord) == s.end() || beginWord == endWord) return res;
        queue<vector<string>> q;
        q.push({beginWord});
        s.erase(beginWord);
        while (!q.empty()) {
            int qs = q.size();
            unordered_set<string> curLvWords;
            while (qs-- > 0) {
                vector<string> cur = q.front();
                beginWord = cur.back();
                q.pop();
                
                bool foundInCurrentWord = false;
                for (int i = 0; i < beginWord.length(); i++) {
                    string newWord = beginWord;
                    for (char c = 'a'; c <= 'z'; c++) {
                        newWord[i] = c;
                        if (s.find(newWord) == s.end())
                            continue;
                        curLvWords.insert(newWord);
                        
                        vector<string> t = cur;
                        t.push_back(newWord);
                        if (newWord == endWord) {
                            foundInCurrentWord = true;
                            res.push_back(t);
                        }
                        q.push(t);
                    }
                    
                    if (foundInCurrentWord) {
                        break;
                    }
                }
            }
            if (curLvWords.find(endWord) != curLvWords.end()) {
                break;
            }
            for (auto & w : curLvWords)
                s.erase(w);
        }
        return res;
    }
};

 

posted @ 2018-11-23 15:07  JTechRoad  阅读(165)  评论(0编辑  收藏  举报