[leetcode] Word Ladder II

题目

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 1:

Input:
beginWord = “hit”,
endWord = “cog”,
wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]

Output:
[
[“hit”,“hot”,“dot”,“dog”,“cog”],
[“hit”,“hot”,“lot”,“log”,“cog”]
]
Example 2:

Input:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,“dot”,“dog”,“lot”,“log”]

Output: []

Explanation: The endWord “cog” is not in wordList, therefore no possible transformation.

思路

这个题目需要寻找的是从原点到目的地点之间的一条路径,这启发我们使用图算法进行寻找:如果两个单词之间只需要切换一个字母就能变换,那么说这两个单词在图中相邻。那么找到一个最小的转换序列等价于找到图中一个从原点到目的地点的最短路径。
这里与寻找最短路径之间一个小小的差别是,这里要找到两点之间所有最短路径。这可以用一种递归的方式寻找:若需要找到某个距离原点n的点的最短路径,那么只需要找到距离原点(n-1)且与目的地相连的所有点,用到达这些点可能的路径连接上这些点,得到的路径集合就是到达目的地点的所有路径。

代码

class Solution {
public:
    vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
        int n = wordList.size();
        int endIdx = -1;
        for(int i = 0; i != n; ++i) {
            if(wordList[i] == endWord) {
                endIdx = i;
            }
        }
        if(endIdx == -1) {
            return vector<vector<string>>();
        }
        vector<vector<bool>> graph(n, vector<bool>(n, false));
        for(int i = 0; i != n; ++i) {
            for(int j = i + 1; j != n; ++j) {
                if(neighbor(wordList[i], wordList[j])) {
                    graph[i][j] = true;
                    graph[j][i] = true;
                }
            }
        }
        vector<int> dist(n, INT_MAX);
        vector<vector<int>> last(n, vector<int>());
        vector<bool> hasVisit(n, false);
        queue<int> wait;
        for(int i = 0; i != n; ++i) {
            if(neighbor(beginWord, wordList[i])) {
                wait.push(i);
                dist[i] = 1;
                last[i].push_back(n);
            }
        }
        while(!wait.empty()) {
            int idx = wait.front();
            wait.pop();
            if(hasVisit[idx]) {
                continue;
            }
            hasVisit[idx] = true;
            for(int i = 0; i != n; ++i) {
                if(!graph[i][idx]) {
                    continue;
                }
                if(dist[i] == INT_MAX) {
                    dist[i] = dist[idx] + 1;
                }
                if(dist[idx] < dist[i]) {
                    last[i].push_back(idx);
                }
                if(!hasVisit[i]) {
                    wait.push(i);
                }
            }
        }
        function<vector<vector<int>> (int)> getpath;
        getpath = [&getpath, &last, &n, &wordList] (int idx) -> vector<vector<int>> {
            if(idx == n) {
                return vector<vector<int>>(1, vector<int>(1, n));
            }
            vector<vector<int>> res;
            for(int i: last[idx]) {
                for(vector<int> path : getpath(i)) {
                    path.push_back(idx);
                    res.push_back(path);
                }
            }
            return res;
        };
        
        auto paths = getpath(endIdx);
        vector<vector<string>> res;
        wordList.push_back(beginWord);
        for(vector<int> path : paths) {
            vector<string> pathStr;
            for(auto iter = path.cbegin(); iter != path.cend(); ++iter) {
                pathStr.push_back(wordList[*iter]);
            }
            res.push_back(pathStr);
            bool i = pathStr[1] < pathStr[2];
        }
        sort(res.begin(), res.end(), [&wordList] (const vector<string>& p1, const vector<string>& p2) -> bool {
            for(int i = 0; i != p1.size(); ++i) {
                if(p1[i] != p2[i]) {
                    return p1[i] > p2[i];
                }
            }
            return false;
        });
        return res;
    }
    bool neighbor(string& str1, string& str2) {
        int diff = 0;
        for(int i = 0; i != str1.size(); ++i) {
            if(str1[i] != str2[i]) {
                ++diff;
            }
        }
        return diff == 1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值