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:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
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.
题意:给定两个单词(起始单词和终止单词),和一本字典。找到从起始单词到终止单词的最短转换路径。
要求:每次只能转换一个字母
每个转换后的单词都必须在字典里面
例如”hit“为起始单词,"cog"为终止单词
字典为{"hot","dot","dog","lot","log"}
其中一条最短路径为"hot","dot","dog","lot","log"
返回长度5
Note:如果没有这样的转换路径,返回0
所有的单词长度都相同
单词中都是小写字母
分类:字符串,图,广度搜索
解法1:广度搜索。使用队列进行广度搜索,将终止单词放进字典,也就是说我们从起始单词开始搜索。
对于起始单词,我们逐个改变它的其中一个字母,生成一个新的单词,然后判断逐个单词是不是在字典里面。
如果是,将这个单词从字典里面取出来放进队列。将该单词从字典取出,并不会影响最短路径。
上述过程,会将起始单词转换一个字母就能达到的,所有在字典里面的单词取出,放入队列
其实就是广度搜索的第一层
然后取队列中的下一个单词,重复上述过程,实现广度搜索。
如果在搜索过程中,碰到了终止单词,返回当前搜索的层次。
原文链接http://blog.csdn.net/crazy__chen/article/details/47335241