【LeetCode】127. 單詞接龍 結題報告 (C++)
阿新 • • 發佈:2018-12-11
題目描述:
給定兩個單詞(beginWord 和 endWord)和一個字典,找到從 beginWord 到 endWord 的最短轉換序列的長度。轉換需遵循如下規則:
每次轉換隻能改變一個字母。 轉換過程中的中間單詞必須是字典中的單詞。 說明:
如果不存在這樣的轉換序列,返回 0。 所有單詞具有相同的長度。 所有單詞只由小寫字母組成。 字典中不存在重複的單詞。 你可以假設 beginWord 和 endWord 是非空的,且二者不相同。 示例 1:
輸入: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
輸出: 5
解釋: 一個最短轉換序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog", 返回它的長度 5。 示例 2:
輸入: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"]
輸出: 0
解釋: endWord "cog" 不在字典中,所以無法進行轉換。
解題方案:
從本題開始,就要學習廣度優先遍歷了。進行廣度優先遍歷,需要使用佇列。
本題解法只是看了大概的意思,寫法有些過於麻煩,以後再進行優化。
class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { queue<string> q; map<string,int> m1; //儲存容器中的字串便於查詢是否存在 map<string,int> re; //儲存結果 int n = wordList.size(); for(int i = 0; i < n; i ++) m1[wordList[i]] = 1; re[beginWord] = 1; q.push(beginWord); while ((!q.empty()) && m1.size()) { string now = q.front(); q.pop(); int num = re[now]; int llen = now.size(); for (int i = 0; i < llen; i ++) { string temp = now; for(char c = 'a' ; c <= 'z'; c ++) { if(temp[i] == c) continue; else temp[i] = c; if(m1.find(temp) != m1.end()) { if(temp == endWord) return num + 1; q.push(temp); re[temp] = num + 1; m1.erase(temp); } } } } return 0; } };