LeetCode 126單詞接龍II(官方解法)

給定兩個單詞(beginWord 和 endWord)和一個字典 wordList,找出所有從 beginWord 到 endWord 的最短轉換序列。轉換需遵循如下規則:

每次轉換隻能改變一個字母。
轉換過程中的中間單詞必須是字典中的單詞。

說明:

如果不存在這樣的轉換序列,返回一個空列表。
所有單詞具有相同的長度。
所有單詞只由小寫字母組成。
字典中不存在重複的單詞。
你可以假設 beginWord 和 endWord 是非空的,且二者不相同。

示例 1:

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

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

示例 2:

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

輸出: []

解釋: endWord “cog” 不在字典中,所以不存在符合要求的轉換序列。

const int INF = 1 << 20;

class Solution {
private:
    unordered_map<string, int> wordId;
    vector<string> idWord;
    vector<vector<int>> edges;
public:
    vector<vector<string>> findLadders(string beginWord, 
                                       string endWord, vector<string>& wordList) {
        int id = 0;
        for (const string& word : wordList) {
            if (!wordId.count(word)) {
                wordId[word] = id++;
                idWord.push_back(word);
            }
        }//創建WORD-ID(unordered_map)映射以及ID-WORD映射(vector<string>)
        if (!wordId.count(endWord)) {
            return {};
        }//不存在目標單詞,返回空
        if (!wordId.count(beginWord)) {
            wordId[beginWord] = id++;
            idWord.push_back(beginWord);
        }//添加起始單詞
        edges.resize(idWord.size());//edges[i][j]表示ID爲i與j的單詞之間有邊(只差一個字母))
        for (int i = 0; i < idWord.size(); i++) {
            for (int j = i + 1; j < idWord.size(); j++) {
                if (transformCheck(idWord[i], idWord[j])) {
                    edges[i].push_back(j);
                    edges[j].push_back(i);
                }
            }
        }//創建edges二維矩陣
        const int dest = wordId[endWord];//dest爲目標單詞的ID
        vector<vector<string>> res;//變化的單詞路徑
        queue<vector<int>> q;//BFS的隊列
        vector<int> cost(id, INF);
        //cost[i] 表示 beginWord 對應的點到第 i 個點的代價(即轉換次數)。
        //初始情況下其所有元素初始化爲無窮大。
        //所有的單詞耗費初始化爲無限遠
        q.push(vector<int>{wordId[beginWord]});//隊列放入起始單詞
        cost[wordId[beginWord]] = 0;
        while (!q.empty()) {
            //將起點加入隊列開始廣度優先搜索,隊列的每一個節點中保存從起點開始的所有路徑。
            vector<int> now = q.front();
            //取出與隊列首單詞相連的單詞ID數組(相差一個字母的單詞數組)爲now
            q.pop();//彈出首單詞ID
            int last = now.back();//last爲now的最後一個ID,即相鄰的最後一個單詞
            /*
             對於每次取出的節點 now,每個節點都是一個數組,數組中的最後一個元素爲當前路徑的最後節點 last:
    		若該節點爲終點,則將其路徑轉換爲對應的單詞存入答案;
    		若該節點不爲終點,則遍歷和它連通的節點(假設爲 to )中
    		滿足 cost[to]>=cost[now]+1的加入隊列,
    		並更新 cost[to]=cost[now]+1。
    		如果 cost[to]<cost[now]+1,
    		說明這個節點已經被訪問過,不需要再考慮。
            */
            if (last == dest) {//若到達終點單詞,將其路徑轉換爲對應的單詞存入答案;
                vector<string> tmp;
                for (int index : now) {//對now數組中的每個單詞ID進行遍歷
                    tmp.push_back(idWord[index]);
                }
                res.push_back(tmp);
            } else {//不爲終點,則遍歷和它連通的節點(假設爲 to )
                for (int i = 0; i < edges[last].size(); i++) {//對ID爲last鄰接的單詞進行掃描
                    int to = edges[last][i];//to爲鄰接的單詞ID
                    if (cost[last] + 1 <= cost[to]) {
                        cost[to] = cost[last] + 1;
                        vector<int> tmp(now);
                        tmp.push_back(to);
                        q.push(tmp);
                    }
                }
            }
        }
        return res;
    }

    bool transformCheck(const string& str1, const string& str2) {
        //檢查它們是否可以通過改變一個字母進行互相轉換。如果可以,則在這兩個點之間建一條雙向邊。
        int differences = 0;//不同字母的個數
        for (int i = 0; i < str1.size() && differences < 2; i++) {
            if (str1[i] != str2[i]) {//對兩個單詞的字母一一對比,有不同的dif自增,大於1則跳出
                ++differences;
            }
        }
        return differences == 1;
    }
};

LeetCode官方題解鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章