当前位置: 首页 > news >正文

212、【图论】字符串接龙(Python)

题目描述

在这里插入图片描述
在这里插入图片描述

题目链接:110. 字符串接龙

代码实现

import collections

n = int(input())
beginStr, endStr = input().split()
strList = [input() for _ in range(n)]


deque = collections.deque()		# 使用队列遍历结点
deque.append([beginStr, 1])		# 存储当前字符串和遍历的到第几个结点
visited = set()					# 存储是否访问过该节点,访问过则跳过
visited.add(beginStr)

while deque:
    word, path = deque.popleft()    
    # 当前字母和目标字母只相差一个时候,跳出
    if sum(1 for a, b in zip(word, endStr) if a != b) == 1:
            print(path + 1)
            exit()
	# 遍历字典
    for next_word in strList:
    	# 下一个字母被构建过边(相差一个时候,构建出边),则跳过
        if next_word in visited:
            continue                
		# 当前字母和下一个字母只相差一个时候,添加遍历
        cnt_distinct = sum(1 for a, b in zip(word, next_word) if a != b)
        if cnt_distinct == 1:
            visited.add(next_word)
            deque.append([next_word, path + 1])
# 遍历完所有节点,均为找到,则跳出            
print(0)

参考文章:超详细的层层递进三种优化及复杂度分析,附双向 BFS 的 PPT, (C++ / Python / Java / Kotlin)

相关文章:

  • Flutter 2025 Roadmap
  • redis 免安装版本 启动方法 windows 安装包
  • 性能比拼: Redis vs Memcached
  • AI Agent类开发应避免Python独舞,奏响多技术交响曲
  • 【cesium】在vue2中使用cesium(持续更新)
  • 基于VSCode的Qt开发‘#include ui_test.h’报错没有该文件
  • 沐渥科技详解氮气柜操作指南
  • C++程序诗篇的灵动赋形:多态
  • 李沐《动手学深度学习》 | 线性神经网络-线性回归
  • 《USB技术应用与开发》第二讲:连接和枚举
  • Python实例题:Python3实现命令行动态进度条
  • WebGPU:前端图形技术的革命性进化与WebGL的未来
  • [ctfshow web入门] web39
  • 深入理解 RxSwift 中的 Driver:用法与实践
  • NI labview数据采集程序
  • wait 和notify ,notifyAll,sleep
  • ecovadis认证有什么好处?ecovadis认证有什么要求 有哪些勋章
  • C++函数签名
  • 工作的意义,在工作以外的地方
  • 从0到1打造一套适合自己接单的脚手架03用户登录注册