LeetCode 126. Word Ladder II (构造最短路径模型)

14 篇文章 0 订阅
3 篇文章 0 订阅

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

  1. Only one letter can be changed at a time
  2. 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.

解法
一开始思路是动态规划,发现这题跟二叉树计数(卡特兰数)问题不一样,信息量太大不好记录。然后想到用图论的方法,对每一个单词都看成一个节点,如果单词之间仅相差一个字母,则两个单词之间有一条路径。我们的目标就是找到所有开始单词到目标单词的最短路径。这里用了dijkstra算法来求解以开始单词为起点到其他单词的最短路径。算完之后用了递归方法构造路径解。
本题需要对单词进行编号,一开始用了一个map来进行编号(以为需要通过string来查找编号,结果不需要用到),结果超时。后来改为一个vector,正常通过了。。
这里用了两种方法找路径,一种是dfs,一种是递归(getpath函数)

class Solution {
public:
    vector<string> words;
    vector<int> G[10000];
    bool vis[10000];
    int d[10000];
    int target;
    vector<vector<string>> ans;
    
    bool connect(string& begin, string& end) {
        int len = begin.size();
        bool err = false;
        for(int i=0;i<len;i++)
            if(begin[i]!=end[i]){
                if(err)
                    return false;
                err = true;
            }
        return true;
    }

    void dijkstra(int s) {
        memset(vis, 0, sizeof(vis));
        priority_queue<pair<int,int>> que;
        fill(d, d+10000, (1<<30));
        d[s] = 0;
        que.push({-d[s], s});
        while(!que.empty()) {
            pair<int,int> tmp = que.top(); que.pop();
            int u = tmp.second;
            vis[u]=true;
            for(int i=0;i<G[u].size();i++) {
                int v=G[u][i];
                if(!vis[v]&&d[v]>d[u]+1) {
                    d[v]=d[u]+1;
                    que.push({-d[v], v});
                }
            }
        }
    }
    
    int path[10000];
    int index;
    vector<vector<string>> getpath(int s){
        vector<vector<string>> res;
        if(s==target) {
            res.push_back({words[s]});
            return res;
        }
        for(int i=0;i<G[s].size();i++) {
            if(d[G[s][i]]==d[s]-1) {
                vector<vector<string>> ans = getpath(G[s][i]);
                for(auto x: ans) {
                    x.insert(x.begin(), words[s]);
                    res.push_back(x);
                }
            }
        }	
        return res;
    }
    
    void dfs(int cur) {
        if (target == cur){ 
            vector<string> tmp;
            for (int i = 0; i < index; i++)
                tmp.push_back(words[path[i]]);
            ans.push_back(tmp);
            return;
        }

        for(int i=0;i<G[cur].size();i++){
            if(!vis[G[cur][i]] && d[G[cur][i]] == d[cur]-1) {
                vis[G[cur][i]] = true;
                path[index++] = G[cur][i];
                dfs(G[cur][i]);
                vis[G[cur][i]] = false;
                index--;
            } 
        }
    }


    vector<vector<string>> findLadders(string begin, string end, vector<string>& list) {
        words = list;
        auto startword = find(words.begin(), words.end(), begin);
        auto endword = find(words.begin(), words.end(), end);
        if(endword == words.end() || begin == end) 
            return vector<vector<string>>();
        if (startword == words.end()) {
            words.push_back(begin);
            startword = find(words.begin(), words.end(), begin);
            endword = find(words.begin(), words.end(), end);
        }
        int n=words.size();
        for (int i = 0; i < n; i++) {
            for (int j = i+1; j < n; j++) {
                if (connect(words[i], words[j])) {
                    G[i].push_back(j);
                    G[j].push_back(i);
                }
            }
        }
        
        int s = startword - words.begin();
        target = endword - words.begin();
        dijkstra(target);
        
        return getpath(s);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值