21. Word Ladder II

Link to the problem

Description

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note:
Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.

Example

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]

Idea

Variant of BFS, need to handle ties properly.

Solution

class Solution {
private:
    void getNeighbors(string curr, unordered_set<string> &dictionary,
                      unordered_map<string, unordered_set<string> > &prev, unordered_set<string> &neighbors) {
        int n = curr.size();
        for (int i = 0; i < n; i++) {
            char orig = curr[i];
            for (int j = 0; j < 26; j++) {
                curr[i] = 'a' + j;
                if (dictionary.find(curr) != dictionary.end() &&
                   prev.find(curr) == prev.end()) {
                    neighbors.insert(curr);
                }
            }
            curr[i] = orig;
        }
    }
    
    void collectPaths(vector<vector<string> > &paths, string curr, string beginWord,
                     unordered_map<string, unordered_set<string> > &prev) {
        if (curr == beginWord) {
            paths.push_back(vector<string> {curr});
        } else if (prev.find(curr) != prev.end()) {
            for (string previous_word : prev[curr]) {
                vector<vector<string> > previous_paths;
                collectPaths(previous_paths, previous_word, beginWord, prev);
                for (auto &previous_path : previous_paths) {
                    previous_path.push_back(curr);
                    paths.push_back(previous_path);
                }
            }
        }
    }

public:
    vector<vector<string> > findLadders(string beginWord, string endWord, vector<string> &wordList) {
        unordered_set<string> dictionary;
        for (auto it = wordList.begin(); it != wordList.end(); ++it) dictionary.insert(*it);
        unordered_map<string, unordered_set<string> > prev;
        prev[beginWord].insert("");
        vector<vector<string> > rtn;
        unordered_set<string> level = {beginWord};
        while (!level.empty()) {
            unordered_set<string> new_level;
            unordered_map<string, unordered_set<string> > new_prev;
            for (string curr : level) {
                if (curr == endWord) {
                    // Summarize the output
                    collectPaths(rtn, curr, beginWord, prev);
                    return rtn;
                }
                unordered_set<string> neighbors;
                getNeighbors(curr, dictionary, prev, neighbors);
                for (string nbr : neighbors) {
                    new_level.insert(nbr);
                    new_prev[nbr].insert(curr);
                }
            }
            for (auto it = new_prev.begin(); it != new_prev.end(); ++it) {
                for (auto &parent : it->second) {
                    prev[it->first].insert(parent);
                }
            }
            level = new_level;
        }
        return rtn;
    }
};

39 / 39 test cases passed.
Runtime: 174 ms

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,261評論 0 23
  • 這一部分著重于介紹Powershell的程序知識,讓我們能夠編寫功能強大的Powershell腳本,執(zhí)行比較復雜的...
    樂百川閱讀 4,534評論 1 16
  • 文/藝莫 時間如流水匆匆過 一輩子說長也長 說短也短 說它長仔細估算 也有幾萬天 說它短 可能就在你不經(jīng)意的 匆匆...
    藝莫閱讀 369評論 10 24

友情鏈接更多精彩內(nèi)容