word Ladder2
来源:互联网 发布:淘宝网长袖t恤高端 编辑:程序博客网 时间:2024/06/15 01:05
[LeetCode]Word Ladder
作者是 发布于 2015年8月17日 在 LeetCode.
题目描述:
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
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.
题目大意:
给定两个单词(beginWord 和 endWord),以及一个字典,寻找从 beginWord 到 endWord 的最短转换序列的长度,满足约束条件:
每次只能改变一个字母
每一个得到的单词必须存在于字典中
例如,给定:
最短的转换序列为:"hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回其长度5。
注意:
如果不存在这样的转换序列,返回0。
所有的单词都是等长的。
所有的单词都只包含小写字母。
解题思路:
方法I:BFS(广度优先搜索)
将wordDict中单词word的每一个字母使用下划线“_”代替,得到wordKey
可以构造wordKey -> word的映射,记为neighbors
- 1
- 2
- 3
- 4
在BFS的执行过程中,将当前单词word的每一位以下划线“_”代替,
在neighbors字典中查找其“相邻”单词(只改变一个字母得到的单词)
Python代码:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
方法II:双向BFS
从起点beginWord和终点endWord同时进行广度优先搜索,执行速度较方法I更快
Python代码:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
本文链接:http://bookshadow.com/weblog/2015/08/17/leetcode-word-ladder/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。
- word ladder2
- word Ladder2
- pongo(csdn英雄会)题解之最小操作数---leetcode之word ladder2
- word
- word
- word
- word
- WORD
- word
- word
- Word
- word
- .word
- word
- Word
- Word
- word
- Word
- 如何搭建大型网站系统
- 剑指offer|旋转数组的最小数字
- 装饰者模式
- JDWP exit error AGENT_ERROR_NO_JNI_ENV(183)
- 一张图带你看懂SpriteKit中Update Loop究竟做了神马!
- word Ladder2
- openGL的安装使用
- socket编程中的一个坑
- 内存溢出
- 1
- ACdream 1210 Chinese Girls' Amusement 大数+思维
- 关于字符串指针的一些问题及字符串的左旋转代码
- 文字无限无缝滚动效果——和派孔明
- 在Jenkins中使用Git托管项目的源码创建Build Job(托管在GitHub上面)