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
的最短路径:
![](http://upload-images.jianshu.io/upload_images/869170-8f0d22a7b8588100.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/585)
PS:图中相互之间只相差一个字母的单词都是相邻节点。
利用BFS算法,维持两个集合: visited 和 wordSet
![](http://upload-images.jianshu.io/upload_images/869170-c490ec68148f6f16.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
从hit开始出发,找到唯一的相邻节点:hot, 把它放进visited中,第一次循环结束。 PS: 所谓找到相邻的节点,在题目中就是找出和该单词之相差一个字母的所有单词。请看最后代码的详细实现。
![](http://upload-images.jianshu.io/upload_images/869170-0d205dd053af3256.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
查看hot节点的所有相邻节点(已经被访问过的hit除外),找到lot和dot, 放进visited中。第二次循环结束。
![](http://upload-images.jianshu.io/upload_images/869170-1f2bd3aaee3d457b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
找出新家进来的lot和dot的未被访问的相邻节点,分别是log和dog放进visited中。第三次循环结束。
![](http://upload-images.jianshu.io/upload_images/869170-94b77120af02de8f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
找出log的未被访问的相邻节点cog,放进结合中。第四次循环结束。由于cog就是endWord,任务结束,跳出循环。
![](http://upload-images.jianshu.io/upload_images/869170-4c079cdd51af4ff9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
这里总共经历了四次循环,每循环一次,其实就是从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, ...
随机推荐
- 自己开发iOS版按键精灵--TTouch
利用闲余时间,把之前的按键录制和播放整理了一些,开发了一个iOS版按键录制.播放的越狱APP,类似按键精灵.触动精灵等按键类的基本功能.脚本采用lua语法格式,可直接执行lua脚本,通过lua和obj ...
- WPF进阶之接口(3):INotifyPropertyChanged,ICommand
INotifiPropertyChanged . 作用:向客户端发出某一属性值已更改的通知.该接口包含一个PropertyChanged事件成员(MSDN的解释) INotifyPropertyCha ...
- NUC972 MDK NON-OS
NUC972直接可以在BSP包里模板进行编程,烧录用Nu writer http://www2.keil.com/mdk5/legacy 下载对应的安装包的插件 是直接下载到DDR 里面去运行,所 ...
- Android APK反编译详解
这段时间在学Android应用开发,在想既然是用Java开发的应该很好反编译从而得到源代码吧,google了一下,确实很简单,以下是我的实践过程. 在此郑重声明,贴出来的目的不是为了去破解人家的软件, ...
- Spring 集合注入
Spring注入是spring框架的核心思想之一.在实际的开发中,我们经常会遇见这样一些类的注入,这些类中包含一些集合作为类的属性,那么要怎样想类中的集合注入数据呢?本文通过一个简单的示例向大家介绍一 ...
- vue+node+mongoDB 火车票H5(六)---城市列表保存到MongoDB数据库并且启用node.js服务
把车站列表保存到数据库,并且从本地创建服务 node.js创建httpserver 1.搭建基于express的运行环境 全局安装express-gengerator cnpm install -g ...
- 160606、springmvc中使用Spring Mobile
springmobile特点: 1.客户端设备识别:识别结果只有3种类型:NORMAL(非手机设备).MOBILE(手机设备).TABLET(平板电脑). 2.网站偏好设置:Spring 通过设备识别 ...
- PAT 甲级 1024 Palindromic Number
1024. Palindromic Number (25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue A ...
- Delphi开发的服务在Windows2003 64位注册方式。
1.在sysWoW32目录下找到cmd.exe,右键运行方式选择administrator,输入密码后.2.TrainServer.exe -install 安装服务.
- 20165330 2017-2018-2《Java程序设计》课程总结
20165330 2017-2018-2<Java程序设计>课程总结 每周作业链接汇总 预备作业1:我期望的师生关系 预备作业2:做中学learning by doing个人感想及学习基础 ...