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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,535评论 0 23
  • 这一部分着重于介绍Powershell的程序知识,让我们能够编写功能强大的Powershell脚本,执行比较复杂的...
    乐百川阅读 9,882评论 1 16
  • 文/艺莫 时间如流水匆匆过 一辈子说长也长 说短也短 说它长仔细估算 也有几万天 说它短 可能就在你不经意的 匆匆...
    艺莫阅读 2,695评论 10 24

友情链接更多精彩内容