題目:
單詞接龍:給定兩個單詞(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" 不在字典中,所以無法進行轉換。
思路:
深度優先使用棧,廣度優先使用隊列。
程序:
from collections import deque
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
if endWord not in wordList:
return 0
# 單詞中缺少一個字母的單詞組合
def make_dict(wordList):
myDcit = {}
for word in wordList:
for index in range(len(word)):
auxiliary = word[: index] + '_' + word[index + 1 :]
myDcit[auxiliary] = myDcit.get(auxiliary, []) + [word]
return myDcit
# 廣度優先
def bfs(beginWord, endWord, myDcit):
# 初始設置為第一步
queue = deque([(beginWord, 1)])
# 保存訪問過的單詞
visited = set()
while queue:
word, step = queue.popleft()
# 訪問沒有訪問過的單詞
if word not in visited:
# 現在訪問了
visited.add(word)
# 判斷是否得到結果
if word == endWord:
return step
for index in range(len(word)):
# 按照現在的word進行查找
auxiliary = word[: index] + '_' + word[index + 1 :]
neighbors = myDcit.get(auxiliary, [])
for neighbor in neighbors:
if neighbor not in visited:
queue.append((neighbor, step + 1))
return 0
myDcit = make_dict(wordList)
return bfs(beginWord, endWord, myDcit)
