【LeetCode 中等題】58-單詞接龍
阿新 • • 發佈:2019-01-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" 不在字典中,所以無法進行轉換。
解法1。用BFS,廣度優先遍歷不需要顯式地建立圖的結構,基本思路是用一個集合來表示可選單詞的集合(為什麼不是列表?因為我們不需要知道索引和重複情況,而集合的查詢時間複雜度只有O(1))。
class Solution(object): def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int """ if beginWord == endWord: return 2 elif not wordList: return 0 wordSet = set(wordList) A = str(beginWord.lower()) B = str(endWord.lower()) q = [A] visited = set([A]) res = 0 #wordSet.add(B) while q: res += 1 for i in range(len(q)): word = q.pop(0) if word == B: return res for w in self.getNextWords(word): if w not in wordSet or w in visited: continue q.append(w) visited.add(w) # 設定visited陣列確保不重複處理詞,也就是不形成環 return 0 def getNextWords(self, word): words = [] for i in range(len(word)): for c in 'abcdefghijklmnopqrstuvwxyz': if word[i] == c: continue new_one = word[:i]+c+word[i+1:] words.append(new_one) return words
參考連結:
https://www.jiuzhang.com/solution/word-ladder/#tag-highlight-lang-python