bfs的一道題。給出start和end的題,還有一組dict,每次只能變一個字母,求最短用多少個詞可以變過去。例子:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
我的思路:首先把dict轉化為set,然后把end也放進去。然后建立一個queue來存放轉化的詞和次序,對于start每個字母從abcd一直變下去,如果在dict中,就存到queue中。然后從queue中出來的詞,如果等于end,那么就說明是最短的路徑了。如果不等于end,就繼續(xù)執(zhí)行上述操作。
如果queue為空都沒找到,那說明就沒有這個詞了。
python代碼:
from collections import deque
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
diction = set(dict)
diction.add(end)
queue = deque()
queue.append((start, 1))
while queue:
word, i = queue.popleft()
if word == end:
return i
for letter in 'abcdefghijklmnopqrstuvwxyz':
for j in range(len(word)):
newword = list(word)
if letter != newword[j]:
newword[j] = letter
newword = ''.join(newword)
if newword in diction:
queue.append((newword, i+1))
diction.remove(newword)
return 0