127. Word Ladder(单词变换 广度优先)
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,
Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
,
return its length 5
.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
这道题是经典的广度有优先搜索的例子,也是Dijkstra's algorithm的变形。
以题目给出的例子为例,其实就是在所有路径的权重都为1的情况下求出下列无向图中从节点hit
到节点cog
的最短路径:

PS:图中相互之间只相差一个字母的单词都是相邻节点。
利用BFS算法,维持两个集合: visited 和 wordSet

从hit开始出发,找到唯一的相邻节点:hot, 把它放进visited中,第一次循环结束。 PS: 所谓找到相邻的节点,在题目中就是找出和该单词之相差一个字母的所有单词。请看最后代码的详细实现。

查看hot节点的所有相邻节点(已经被访问过的hit除外),找到lot和dot, 放进visited中。第二次循环结束。

找出新家进来的lot和dot的未被访问的相邻节点,分别是log和dog放进visited中。第三次循环结束。

找出log的未被访问的相邻节点cog,放进结合中。第四次循环结束。由于cog就是endWord,任务结束,跳出循环。

这里总共经历了四次循环,每循环一次,其实就是从beginWord想endWord变化的一步,因此循环的次数(加上1)就是从beginWord想endWord转变经历的 number of steps。
class Solution:
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
wordList = set(wordList)
visited = [beginWord]
visited = set(visited)
dist = 1 while endWord not in visited:
temp = set()
for word in visited:
for i in range(len(word)):
newwordL = list(word)
for ch in 'qwertyuiopasdfghjklzxcvbnm':
newwordL[i] = ch
newWord = ''.join(newwordL)
if newWord in wordList:
temp.add(newWord)
wordList.remove(newWord) dist += 1
if len(temp) == 0: # if 0, it never gets to the endWord
return 0 visited = temp return dist
参考链接:https://www.jianshu.com/p/753bd585d57e
127. Word Ladder(单词变换 广度优先)的更多相关文章
- [LeetCode] 127. Word Ladder 单词阶梯
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...
- LeetCode 127. Word Ladder 单词接龙(C++/Java)
题目: Given two words (beginWord and endWord), and a dictionary's word list, find the length of shorte ...
- 127 Word Ladder 单词接龙
给出两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列,转换需遵循如下规则: 每次只能改变一个字母. 变换过程中的 ...
- [leetcode]127. Word Ladder单词接龙
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...
- leetcode 127. Word Ladder、126. Word Ladder II
127. Word Ladder 这道题使用bfs来解决,每次将满足要求的变换单词加入队列中. wordSet用来记录当前词典中的单词,做一个单词变换生成一个新单词,都需要判断这个单词是否在词典中,不 ...
- 127. Word Ladder(M)
127. Word LadderGiven two words (beginWord and endWord), and a dictionary's word list, find the leng ...
- 【LeetCode】127. Word Ladder
Word Ladder Given two words (start and end), and a dictionary, find the length of shortest transform ...
- 127 Word Ladder
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest t ...
- Leetcode#127 Word Ladder
原题地址 BFS Word Ladder II的简化版(参见这篇文章) 由于只需要计算步数,所以简单许多. 代码: int ladderLength(string start, string end, ...
随机推荐
- BestCoder Round #12 War(计算几何)
War Time Limit: 8000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submis ...
- jquery后加Dom绑定事件
$('#musicCategoryListContainer').on('click', '.musicCategoryItem', function () { $(this).siblings(). ...
- iOS:友盟SDK第三方登录 分享及友盟统计的使用
本文转载至 http://www.it165.net/pro/html/201503/37101.html Tag标签:第三方 01.#import "UMSocial.h" ...
- php实现简单的权限管理
今天主要来实现一个权限管理系统,它主要是为了给不同的用户设定不同的权限,从而实现不同权限的用户登录之后使用的功能不一样,首先先看下数据库 总共有5张表,qx_user,qx_rules和qx_jues ...
- Android实现“退出确认”对话框
@Override public void onBackPressed() { new AlertDialog.Builder(this).setTitle("确认退出吗?") . ...
- Django--20170905--笔记
一.django的安装 1.先安装python 2.再安装django:pip install django 3.使用虚拟环境:pip install virtualenv 二.项目的创建 1.可以先 ...
- .net应用程序安装部署时异常 Error 1001. 在初始化安装时发生异常 System.BadImageFormatException:未能加载文件或程序集 的解决办法【成功解决】
采用.net 4.0框架开发的一个桌面应用程序在某学校的一体机(Windows7的32位操作系统)上做安装部署时抛出异常,安装程序回滚,多次尝试仍不成功. Error 1001. 在初始化安装时发生异 ...
- C# ArcEngine 实现点击要素高亮并弹出其属性
本文是模仿ArcMap里面的Identify(识别)功能,通过点击要素,使其高亮显示并弹出其属性表!本文只做了点击查询! 本文所用的环境为VS2010,AecEngine基于C#语言,界面是用Dev做 ...
- PMP私有广告交易市场
[资源]互联网广告新知:半小时读懂PMP私有广告交易市场是什么? https://socialbeta.com/t/resource-what-is-pmp.html SocialBeta | 201 ...
- If a cache file exists, it is sent directly to the browser, bypassing the normal system execution.
w开启缓存,缓存视图,用于后续请求. https://www.codeigniter.com/userguide3/overview/appflow.html http://codeigniter.o ...