[LeetCode]题解(python):127-Word Ladder

本文提供了一种解决LeetCode单词阶梯问题的有效方法,通过广度优先搜索算法找到从开始单词到目标单词的最短转换路径。代码使用Python实现,并详细展示了如何遍历可能的单词组合来寻找最短路径。

题目来源:

  https://leetcode.com/problems/word-ladder/


 

题意分析:

  和上一题目类似,给定一个beginWord和一个endWord,以及一个字典list。这题需要的是要beginWord转化成endWord的最短路径长度。


 

题目思路:

  最短路的思路。将beginWord放进队列,如果队列不为空,那么取出第一个数,将其周围的在字典的字符放进队列,直到周围的存在endword。


 

代码(python):

  

 1 import Queue
 2 class Solution(object):
 3     def ladderLength(self, beginWord, endWord, wordList):
 4         """
 5         :type beginWord: str
 6         :type endWord: str
 7         :type wordList: Set[str]
 8         :rtype: int
 9         """
10         q,ans = Queue.Queue(),{}
11         q.put(beginWord);wordList.add(endWord)
12         ans[beginWord] = 1
13         while not q.empty():
14             tmp = q.get()
15             if tmp == endWord:
16                 return ans[endWord]
17             for i in range(len(tmp)):
18                 part1,part2 = tmp[:i],tmp[i+1:]
19                 for j in 'abcdefghijklmnopqrstuvwxyz':
20                     if tmp[i] != j:
21                         newword = part1 + j + part2
22                         if newword in wordList:
23                             q.put(newword)
24                             ans[newword] = ans[tmp] + 1
25                             wordList.remove(newword)
26         return 0
27                         
View Code

 

转载于:https://www.cnblogs.com/chruny/p/5306671.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值