Word Ladder II

来源:互联网 发布:农夫山泉瓶子尺寸数据 编辑:程序博客网 时间:2024/05/20 04:15

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 intermediate word must exist in the word list
For example,

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

[
[“hit”,”hot”,”dot”,”dog”,”cog”],
[“hit”,”hot”,”lot”,”log”,”cog”]
]

Note:
All words have the same length.
All words contain only lowercase alphabetic characters.

这道题目与Word Ladder I 相比难度有所提升,这道题目在leetcode所有题目中的通过率是最低的,其实并不是题目所涉及到的算法有多么的难,而是对时间要求非常的严格

思路

1.  先通过BFS 找到从start->end 最短路径中每个字符串的前驱集合(prve)2.  在通过DFS对所有的路径进行枚举,这时候是从end开始逐步向前搜索知道start停止,所以最后结果还需要做一下reverse

代码

class Solution {public:    vector<vector<string> > findLadders(string start, string end, unordered_set<string> &dict) {        vector<vector<string> > ans;        if(start == end) return ans;        unordered_set<string> visit;        //记录路径中每个节点的所有前驱节点        unordered_map<string, vector<string> > prev;        unordered_set<string> current, next;        current.insert(start);        visit.insert(start);        bool found = false;        while(!current.empty() && !found) {            //标记所有已经访问过的节点,避免重复访问            for(auto& str : current) {              visit.insert(str);            }            for(auto str : current) {                int n = str.size();                for(int i = 0; i < n; ++i) {                    for(char ch = 'a'; ch <= 'z'; ++ch) {                        if(ch == str[i]) continue;                        string tmp = str;                        tmp[i] = ch;                        if(tmp == end) found = true;                        //因为需要记录所有的前驱所以不能在里面设置visit, 并且用unordered_set是为了避免重复                        if(dict.find(tmp) != dict.end() && visit.find(tmp) == visit.end()) {                            next.insert(tmp);                            prev[tmp].push_back(str);                        }                    }                }            }            current.clear();            swap(current, next);        }        if(found) {            vector<string> path;            dfs(ans, prev, path, start, end);        }        return ans;    }    void dfs(vector<vector<string> >& ans,  unordered_map<string, vector<string> >& prev, vector<string>& path, string& start, string& end) {        path.push_back(end);        if(start == end) {            ans.push_back(path);            reverse(ans.back().begin(), ans.back().end());            path.pop_back();            return;        }        //逐层,逐个节点搜索        auto que = prev.find(end)->second;        for(auto& x : que) {            dfs(ans, prev, path, start, x);        }        path.pop_back();    }};
0 0
原创粉丝点击