LeetCode —— 单词接龙(Python)

本文介绍了一种利用广度优先搜索(BFS)算法解决单词梯形问题的方法,通过构建单词字典并查找从开始单词到目标单词的最短转换路径。文章详细展示了如何通过变换一个字母来生成新的有效单词,并通过实例代码讲解了具体实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用字典,降低查找的复杂度。使用list会超时。

 

 1 class Solution:
 2 
 3     def nextWordsList(self, word, wordDict):
 4         res_list = []
 5         for i in range(len(word)):
 6             for j in string.ascii_lowercase:
 7                 new_word = list(word)
 8                 if j != word[i]:
 9                     new_word[i] = j
10                     new_word = ''.join(new_word)
11                     if new_word in wordDict:
12                         res_list.append(new_word)
13                         del wordDict[new_word]
14         return res_list
15 
16 
17     def bfs(self, beginWord, endWord, wordDict):
18         # 返回一个int
19         queue = []
20         queue.append([beginWord, 1])
21         while queue:
22             word, step = queue[0][0], queue[0][1]
23             queue.pop(0)
24             if word == endWord: return step
25             # 得到下一次变换一个单词,得到的单词列表
26             nextWords = self.nextWordsList(word, wordDict)
27             for j in nextWords:
28                 queue.append([j, step+1])
29         return 0
30     def ladderLength(self, beginWord, endWord, wordList):
31         """
32         :type beginWord: str
33         :type endWord: str
34         :type wordList: List[str]
35         :rtype: int
36         """
37         if beginWord in wordList: wordList.remove(beginWord)
38         wordDict = {}
39         for w in wordList: wordDict[w] = 1
40         return self.bfs(beginWord, endWord, wordDict)

 

转载于:https://www.cnblogs.com/yxh-amysear/p/9575305.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值