1. 程式人生 > >LeetCode 126. Word Ladder II (構造最短路徑模型)

LeetCode 126. 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:

  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);
    }
};