zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):广度优先搜索类:第127题:单词接龙:给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则: 每次转换只能改变一个字母。 转换过程中的中间单词必须是字典中的单词。

    题目:

    单词接龙:给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则:  每次转换只能改变一个字母。 转换过程中的中间单词必须是字典中的单词。 

    说明:

    如果不存在这样的转换序列,返回 0。
    所有单词具有相同的长度。
    所有单词只由小写字母组成。
    字典中不存在重复的单词。
    你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
    示例 1:

    输入:
    beginWord = "hit",
    endWord = "cog",
    wordList = ["hot","dot","dog","lot","log","cog"]

    输出: 5

    解释: 一个最短转换序列是 "hit" -> "hot" -> "dot" -> "dog" -> "cog",
    返回它的长度 5。
    示例 2:

    输入:
    beginWord = "hit"
    endWord = "cog"
    wordList = ["hot","dot","dog","lot","log"]

    输出: 0

    解释: endWord "cog" 不在字典中,所以无法进行转换。

    思路:

    深度优先使用栈,广度优先使用队列。

    程序:

    from collections import deque
    class Solution:
        def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
            if endWord not in wordList:
                return 0
            # 单词中缺少一个字母的单词组合
            def make_dict(wordList):
                myDcit = {}
                for word in wordList:
                    for index in range(len(word)):
                        auxiliary = word[: index] + '_' + word[index + 1 :]
                        myDcit[auxiliary] = myDcit.get(auxiliary, []) + [word]
                return myDcit
            # 广度优先
            def bfs(beginWord, endWord, myDcit):
                # 初始设置为第一步
                queue = deque([(beginWord, 1)])
                # 保存访问过的单词
                visited = set()
                while queue:
                    word, step = queue.popleft()
                    # 访问没有访问过的单词
                    if word not in visited:
                        # 现在访问了
                        visited.add(word)
                        # 判断是否得到结果
                        if word == endWord:
                            return step
                        for index in range(len(word)):
                            # 按照现在的word进行查找
                            auxiliary = word[: index] + '_' + word[index + 1 :]
                            neighbors = myDcit.get(auxiliary, [])
                            for neighbor in neighbors:
                                if neighbor not in visited:
                                    queue.append((neighbor, step + 1))
                return 0
            myDcit = make_dict(wordList)
            return bfs(beginWord, endWord, myDcit)
    

      

  • 相关阅读:
    理论+实践解析“IT治理”之模式与原则
    iOS开发如何避免安全隐患
    DBA职业发展之路:去“IOE”等挑战之下,DBA将何去何从?
    自动化测试最佳实践(一):从纺锤模型到金字塔模型
    宜信开源|手把手教你安装第一个LAIN应用
    宜信开源|数据库审核软件Themis的规则解析与部署攻略
    开源|性能优化利器:数据库审核平台Themis的选型与实践
    小老板,我300M的网,网速很慢怎么办?
    JSP、ASP、PHP Web应用程序怎么这么多P!
    难道你现在还不知道:C/S和B/S
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12970677.html
Copyright © 2011-2022 走看看