描述
给出两个单词(start和end)和一个字典,找到从start到end的最短转换序列
比如:
每次只能改变一个字母。
变换过程中的中间单词必须在字典中出现。
如果没有转换序列则返回0。
所有单词具有相同的长度。
所有单词都只包含小写字母。
样例
给出数据如下:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
一个最短的变换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
返回它的长度 5
import collections
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return an integer
def ladderLength(self, start, end, dict):
# write your code here
dict.add(end)
wordLen = len(start)
queue = collections.deque([(start, 1)])
while queue:
curr = queue.popleft()
currWord = curr[0]; currLen = curr[1]
if currWord == end: return currLen
for i in range(wordLen):
part1 = currWord[:i]; part2 = currWord[i+1:]
for j in 'abcdefghijklmnopqrstuvwxyz':
if currWord[i] != j:
nextWord = part1 + j + part2
if nextWord in dict:
queue.append((nextWord, currLen + 1))
dict.remove(nextWord)
return 0