Lintcode 120. Word Ladder

2018-12-17  本文已影响0人  woniudear

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,就继续执行上述操作。
如果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
上一篇下一篇

猜你喜欢

热点阅读