zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    isequal 和startswith 使用
    UVa10340
    UVa1368
    UVa455
    UVa1225
    UVa1586
    UVa 1585
    UVa10082
    UVa272
    NYOJ1
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/10007710.html
Copyright © 2011-2022 走看看