美文网首页
[Hard BFS] Word Ladders

[Hard BFS] Word Ladders

作者: Mree111 | 来源:发表于2019-10-24 21:44 被阅读0次

Description

给出两个单词(start和end)和一个字典,找出从start到end的最短转换序列,输出最短序列的长度。

变换规则如下:

每次只能改变一个字母。
变换过程中的中间单词必须在字典中出现。(起始单词和结束单词不需要出现在字典中)

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):
        dict.add(end)
        queue = collections.deque([start])
        visited = set([start])
        
        distance = 0
        while queue:
            distance += 1
            for i in range(len(queue)):
                word = queue.popleft()
                if word == end:
                    return distance
                
                for next_word in self.get_next_words(word):
                    if next_word not in dict or next_word in visited:
                        continue
                    queue.append(next_word)
                    visited.add(next_word) 

        return 0
        
    # O(26 * L^2)
    # L is the length of word
    def get_next_words(self, word):
        words = []
        for i in range(len(word)):
            left, right = word[:i], word[i + 1:]
            for char in 'abcdefghijklmnopqrstuvwxyz':
                if word[i] == char:
                    continue
                words.append(left + char + right)
        return words

相关文章

  • [Hard BFS] Word Ladders

    Description 给出两个单词(start和end)和一个字典,找出从start到end的最短转换序列,输出...

  • Word Hard Play Hard

    你在小池塘里呆的很好,泥鳅很丑但会说喜庆话,癞蛤蟆很马虎但有趣,小鲫鱼是你们共同的女神,有一天你听说江河湖海哪个都...

  • ORID27

    [127] Word Ladder解题报告 BFS算法 用什么算法?这道题需要用 BFS为什么用这个算法(那些条件...

  • OWW CH18

    WORD AND EXPRESSION They will trot out the hard-won words...

  • Seems easy, hardly understand

    It seems that almost every word is known, but it’s hard t...

  • 30 Substring with Concatenation

    30Substring with Concatenation of All Words19.6%Hard数word...

  • Life never gives you a choice

    Life is hard to say in one word Sometimes I don't have th...

  • The feelings of 《You have reason

    There is a saying which goes that, "Books are the ladders...

  • 126 Word Ladder II

    126Word Ladder II13.2%Hard所有的words可以组成一张图。节点是word,如果有一个字母...

  • * 301. Remove Invalid Parenthese

    果然是hard的题,看起来DFS比BFS会好些。直接看答案了。 这种符号是不是valid的题,应该首先想到cnt这...

网友评论

      本文标题:[Hard BFS] Word Ladders

      本文链接:https://www.haomeiwen.com/subject/ccrtvctx.html