使用python完成这个题目: 126. 单词接龙 II 困难 663 相关企业 按字典 wordList 完成从单词 beginWord 到单词 endWord 转化,一个表示此过程的 转换序列 是形式上像 beginWord -> s1 -> s2 -> ... -> sk 这样的单词序列,并满足: 每对相邻的单词之间仅有单个字母不同。 转换过程中的每个单词 si(1 <= i <= k)必须是字典 wordList 中的单词。注意,beginWord 不必是字典 wordList 中的单词。 sk == endWord 给你两个单词 beginWord 和 endWord ,以及一个字典 wordList 。请你找出并返回所有从 beginWord 到 endWord 的 最短转换序列 ,如果不存在这样的转换序列,返回一个空列表。每个序列都应该以单词列表 [beginWord, s1, s2, ..., sk] 的形式返回。 示例 1: 输入:beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] 输出:[["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]] 解释:存在 2 种最短的转换序列: "hit" -> "hot" -> "dot" -> "dog" -> "cog" "hit" -> "hot" -> "lot" -> "log" -> "cog"
时间: 2023-07-17 16:04:02 浏览: 94
126. 单词接龙 II
下面是使用Python完成题目的代码示例:
```python
from collections import defaultdict, deque
def findLadders(beginWord, endWord, wordList):
# 构建单词到ID的映射关系
wordId = defaultdict(int)
idWord = []
for word in wordList:
if word not in wordId:
wordId[word] = len(idWord)
idWord.append(word)
if endWord not in wordId:
return []
# 构建图
graph = defaultdict(list)
for word in wordList:
for i in range(len(word)):
mask = word[:i] + '*' + word[i+1:]
graph[word].append(wordId[mask])
graph[wordId[mask]].append(wordId[word])
# 使用BFS找到最短路径
res = []
visited = defaultdict(bool)
queue = deque([(wordId[beginWord], [[beginWord]])])
minLevel = float('inf')
while queue:
curWord, path = queue.popleft()
if len(path) > minLevel:
break
if curWord == wordId[endWord]:
res.append(path)
minLevel = len(path)
for neighbor in graph[curWord]:
if not visited[neighbor]:
visited[neighbor] = True
queue.append((neighbor, path + [idWord[neighbor]]))
return res
# 测试样例
beginWord = "hit"
endWord = "cog"
wordList = ["hot", "dot", "dog", "lot", "log", "cog"]
result = findLadders(beginWord, endWord, wordList)
print(result)
```
这段代码使用了广度优先搜索(BFS)来寻找最短路径。首先构建单词到ID的映射关系,然后构建图,图中的每个节点是一个单词,如果两个单词只有一个字母不同,则它们之间有一条边。接下来,使用BFS找到最短路径,并将结果存储在变量`res`中。最后,打印结果。
希望能对您有所帮助!
阅读全文