【算法】Word Ladder II单词接龙

Word Ladder/ Word Ladder II 题目分析 1. Word Ladder和Word Ladder II两题是连续的,基本是同一个问题的两个难度,因此放在一起做了。 2. Word Ladder是要找出一条从Start Word 到 End Word的最短路径,一个比较简单的想法就是建立一张图,描述每个在字典中的词之间的可达性,只有任意两个词间有且仅有一个字母不同的时候是直接可达的,然后用BFS的方式去找到Start Word和 阅读详情

Word Ladder II 寻找字梯

题目

Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
For example,

Given:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,“dot”,“dog”,“lot”,“log”,“cog”]

Return

[
[“hit”,“hot”,“dot”,“dog”,“cog”],
[“hit”,“hot”,“lot”,“log”,“cog”]
]
Note:

Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.

给出字梯的头单词和尾单词,以及一组单词,找出相邻单词只有一个字符不同的一组单词
可以假设字符串复合如下条件:

  1. 所有单词长度相同
  2. 所有单词均为小写
  3. 没有重复单词
  4. 头单词和尾单词不为空且不相同

解题思路

  1. 判断单词数组是否含有尾单词,不含有则没有接龙,返回空
  2. 用二维数组实现相邻单词路径图,可一步到达置为true,反之为false
  3. 用BFS寻找每个节点的前置节点
  4. 用DFS找到从尾节点到头节点的路径并放入容器
  5. 返回容器

代码实现

//
//  AlgorithmManager+WordLadder2.swift
//  EGSwiftLearning
//
//  Created by Easer Liu on 2019/11/19.
//  Copyright © 2019 Easer. All rights reserved.
//

import Foundation
//最终结果的容器
var listList = [[String]]();
//最终结果的临时容器
 var tempPath = [Int]()
//用于存储节点到头节点的步数
 var d = [Int]();
//用于存储节点的前置节点数量
 var countInq = [Int]();
//用于判断节点是否在队列中
 var inq = [Bool]();
//用于存储节点的前置节点序号
 var pre = [Set<Int>]();
extension AlgorithmManager{
    class func WordLadder2Solution(_ beginWord: String, _ endWord: String, _ wordList: [String]) -> [[String]] {
//        将列表和头单词放入Set中
        var hashSet = Set<String>();
        hashSet = hashSet.union(wordList);
        hashSet.insert(beginWord);
//        如果其中不包含尾单词,则不存在单词接龙,直接返回空
        if(!hashSet.contains(endWord)){
            return [[String]]();
        }
        
        //清空容器
        listList.removeAll();
        tempPath.removeAll();
        d.removeAll();
        countInq.removeAll();
        inq.removeAll();
        pre.removeAll();
        
//        将单词加入到list中,并记录头单词和为单词的序号
        var index = 0;
        var start = 0;
        var end = 0;
        var list = [String]()
        for s in hashSet {
            list.append(s)
            if s == beginWord {
                start = index;
            }
            if s == endWord {
                end = index;
            }
            index += 1
        }
//        获得单词的数量,并初始化图,
        let size = list.count;
        var graph = [[Bool]]();
        for i in 0 ..< size{
            graph.append([Bool]())
            d.append(Int.max)
            countInq.append(0)
            pre.append(Set<Int>())
            inq.append(false)
        for _ in 0 ..< size {
            graph[i].append(false)
            }}
//        将图中可一步到达的两个单词位置设置为true
        for i in 0 ..< size {
            for j in i+1 ..< size {
                if self.HasPath(word1: list[i], word2: list[j]) {
                    graph[i][j] = true;
                    graph[j][i] = true;}
            }
        }
//        广度优先,配置图中每个节点的前置节点
        self.BFS(start: start, list: list, graph: graph)
//        深度优先,寻找从尾节点到头节点的路径
        self.DFS(start: start, nowVisit: end, list: list)
        
        
//        返回结果
        print(listList)
                return listList;
    }
//    判断两个单词之间是否可一步到达
    class func HasPath(word1:String, word2:String) -> Bool{
        var count = 0
        let word1Arr = Array(word1)
        let word2Arr = Array(word2)
//        遍历两个单词的字符并对比
        for i in 0 ..< word1.count {
//            若字符不相同,则count+1
            if word1Arr[i] != word2Arr[i] {
                count += 1
            }
        }
//        若count为1,则说明只有一个字符相同,则可以一步到达
        if count == 1 {
            return true
        }
//        否则不能一步到达
        return false
    }
//    广度优先,配置节点的前置节点pre
    class func BFS(start:Int, list:[String], graph:[[Bool]]) -> Bool{
//        单词数量
        let size = list.count;
//        头节点到头节点的j步数为0
        d[start] = 0;
//        初始化队列并将头节点序号放入
        var queue = [Int]()
        queue.append(start)
        var headIndex = 0
        var tailIndex = 1
        let modulo = 10000000000
        countInq[start] += 1;
        inq[start] = true;
//        广度优先算法
        while headIndex != tailIndex {
//            出队节点序号
            let u = queue[headIndex];
            headIndex = (1 + headIndex) % modulo
            inq[u] = false;
//            遍历列队序号设置前置节点
            for v in 0 ..< size {
//                若u节点可一步到达v节点,则配置前置节点
                if(graph[u][v]){
//                    若u节点到头节点的步数+1小于v节点到头节点的步数,则清空v节点的前置节点,并将u节点加入
                    if(d[u] + 1 < d[v]) {
                        pre[v].removeAll();
                        pre[v].insert(u);
                        d[v] = d[u] + 1;
//                        若jv节点没有入队则入队
                        if (!inq[v]) {
                            queue.append(v);
                            tailIndex = (1 + tailIndex) % modulo
                            countInq[v]+=1;
                            inq[v] = true;
                            if (countInq[v] > size - 1) {
                                return false;
                            }
                        }
//                    若u节点到头节点的步数+1等于v节点到头节点的步数,则将u节点加入

                    }else if(d[u] + 1 == d[v]){
                        pre[v].insert(u);
//                        若jv节点没有入队则入队
                        if (!inq[v]) {
                            queue.append(v);
                            tailIndex = (1 + tailIndex) % modulo
                            countInq[v]+=1;
                            inq[v] = true;
                            if (countInq[v] > size - 1) {
                                return false;
                            }
                        }
                    }
                }
            }
        }
        
        return true
    }

//    深度优先,寻找单词接龙
    class func DFS(start:Int, nowVisit:Int, list:[String]) -> (){
//        将当前节点加入临时容器
        tempPath.append(nowVisit)
//        若当前节点为头节点,说明已经找到单词接龙
                if(nowVisit == start){
//                    遍历临时容器,将结果放入到listList
                    var path = [String]()
                    for i in stride(from:tempPath.count-1, through:0, by:-1) {
                        path.append(list[tempPath[i]])
                    }
                    listList.append(path);
//                    删除最后一个节点
                    tempPath.remove(at: tempPath.count - 1);
                    return;
                }
//        遍历当前节点的前置节点,并递归
        for integer in pre[nowVisit] {
            self.DFS(start: start, nowVisit: integer, list: list)
        }
//        删除最后一个节点
                tempPath.remove(at: tempPath.count - 1);
    }
}

最终LeetCode上时间超限,应该还有待改善
代码地址:https://github.com/sinianshou/EGSwiftLearning

螺丝锁付系统软件设计 C# Winform 视觉螺丝锁付系统软件设计 C# Winform ,这是其中通信子模块设计 阅读详情

相关推荐

Python CalmAn(Calcium Imaging Analysis)神经生物学工具包安装及环境配置过程

CalmAn是一个用于大规模钙成像数据分析和行为分析的Python工具箱。CaImAn实施了大规模钙成像数据分析管道中所需的一套基本方法。针对多天的运动校正、源提取、尖峰反褶积和分量配准,实现了快速且可扩展的算法。它适用于双光子和单光子荧光显微镜数据,可以在批处理和在线模式下运行;CaImAn还包含一些分析摄像机行为的例程。

Fine的优快云博客 3557

【Leetcode】126. Word Ladder II

题目地址: https://leetcode.com/problems/word-ladder-ii/ 给定两个单词作为起点和终点,每一步允许从单词中改变某个位置的字母,变为另一个单词。再给定一个单词的列表,问从起点到终点的所有最短路径,要求路径中所有单词都要在列表里(起点不必在,终点必须在)。题目保证所有单词都由小写字母组成。 思路是BFS建图 + DFS。先从起点出发,用BFS的方式找到终点,并一路建图,建图的时候需要注意,BFS的同层的单词之间不要连边,每条边只在不同层的单词连起来。并且,一旦发现到了

数学、算法爱好者的博客 491

SAP生产订单(创建-下达-发料-报工-入库)全流程及反向流程

SAP创建下达报工入库发料以及取消发料取消入库,批量下达删除关闭,生产订单出入库查询和状态更改查询记录

weixin_38974136的博客 2万+

[Leetcode] 126 Word Ladder II 解题 (和127的对比)

Loading...https://leetcode.com/problems/word-ladder-ii/ 这道题区别于127 Word Ladder 在于 1. 127求的是最短路径长度;本题求的是最短路径 2. 127 求的是一个值,本题求的是所有的最短路径 为了解决这个变化,关键点是 1. 对于上一层之前访问的节点我们不能再访问了 2. 对于下一层要访问的节点,我们要记录所有的路径。 class Solution: def findLadders(self, be.

sdhfaka的专栏 247

Flutter模块打包AAR集成Android原生项目实践

跨平台开发框架Flutter通过将UI组件渲染为原生代码实现高性能表现,其核心优势在于一套代码可同时运行在iOS和Android平台。在工程实践中,将Flutter模块打包为AAR(Android Archive)进行集成,成为混合开发的主流方案。这种方案既保留了原生项目的稳定性,又能渐进式引入Flutter的高效开发特性。通过配置MethodChannel实现原生与Dart代码通信,开发者可以灵活控制Flutter引擎生命周期,优化内存占用和渲染性能。对于电商、社交等需要快速迭代的业务场景,该方案能显著提

weixin_34025051的博客 398

NVIDIA驱动版本太低?手把手教你解决CUDA与PyTorch版本冲突问题

本文针对深度学习开发中常见的NVIDIA驱动版本过低导致的CUDA与PyTorch版本冲突问题,提供了从根源理解到实战解决的完整指南。文章详细解析了驱动、CUDA与PyTorch的依赖关系,并给出了升级驱动、降级PyTorch、使用Conda环境管理及Docker容器化四种核心解决方案,帮助开发者快速诊断并构建稳定的GPU开发工作流。

grpc6streamer的博客 968

word-ladder-ii(字梯)

1.题目 给定两个单词(开始和结束)和一个字典,从头到尾查找所有最短的变换序列,以便: 一次只能更改一个字母 每个中间词必须存在于词典中 例如,给定: start ="hit" end ="cog" dict =["hot","dot","dog","lot","log"] 返回: [ ["hit","hot",&quo

ShuJk的博客 456

如何使用JMeter进行大模型的压力测试?

使用JMeter进行大模型的压力测试,核心是通过模拟高并发请求,测试大模型在极限负载下的性能表现(如响应时间、吞吐量、错误率、资源瓶颈等)。通过以上步骤,可系统性评估大模型在高压下的性能极限,为优化模型(如量化、蒸馏)、扩容硬件(增加GPU)或调整接口限流策略提供数据依据。)、请求方式(POST)、认证方式(API Key放在Header)、请求参数(作用:避免瞬间高压压垮系统,更精准找到瓶颈点。等)、响应格式(同步/流式)。需获取:API地址(如。通过CSV文件引入不同。

alankuo的专栏 787

Word Ladder II -- leetcode

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: Only one letter can be changed at a timeEach intermediate word must exi

elton_xiao的专栏 584

基于点云数据的统计滤波算法改进

随着三维视觉和点云处理技术的发展,点云数据在机器人、自动驾驶、增强现实等领域得到了广泛应用。而点云数据中常常包含着各种噪声和异常点,这些噪声和异常点会影响后续的数据处理和分析任务。因此,对点云数据进行滤波处理是必不可少的一步。在点云滤波算法中,统计滤波(Statistical Filtering)是一种常见且有效的方法。它通过对点云数据进行统计分析,将噪声和异常点剔除或修复,从而得到更为准确和可靠的点云数据。本文将介绍一种改进的统计滤波算法,并提供相应的源代码实现。

QfcaLinux的博客 291

锂电池SOH预测 | 基于BP神经网络的锂电池SOH预测(附matlab完整源码)

锂电池SOH预测 | 基于BP神经网络的锂电池SOH预测(附matlab完整源码)

天天酷科研的博客 1113

LeetCode-Go 题解:127. Word Ladder 单词接龙 BFS 最短转换序列

本文基于开源仓库 LeetCode-Go([README.md](https://link.gitcode.com/i/756004789fd2f88296a4c6f292414cba))中 [0127.Word-Ladder](https://link.gitcode.com/i/e157ce2540f29a6abbb5da563ac8358f) 的题解文档,完整讲解 LeetCode 第 12

gitblog_00553的博客 854

麒麟操作系统安装教程(保姆级)

本文介绍了如何在VM中安装麒麟操作系统,文章详细的介绍了麒麟操作系统按钻过步骤。

啊渊的专栏 1万+

Leetcode 126.单词接龙 II(Word Ladder II)

Leetcode 126.单词接龙 II 1 题目描述(Leetcode题目链接)   给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则: 每次转换只能改变一个字母。 转换过程中的中间单词必须是字典中的单词。 说明: 如果不存在这样的转换序列,返回一个空列表。 所有单词具有相同的长度。 所有单词只由小写字母组成。 字典中不存在重复的单词。 你可以假设 beginWord 和 end

qq_39378221的博客 268

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

LeetCode | 0127. Word Ladder单词接龙【Python】

LeetCode 0127. Word Ladder单词接龙【Medium】【Python】【BFS】 Problem LeetCode Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from b...

Wonz 640

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

【LeetCode】 126. Word Ladder II 单词接龙 II(Hard)(JAVA)

【LeetCode】 126. Word Ladder II 单词接龙 II(Hard)(JAVA) 题目地址: https://leetcode.com/problems/word-ladder-ii/ 题目描述: Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such

qq_16927853的博客 249

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

LeetCode-BFS-127-M:单词接龙 (Word Ladder)

文章目录思路-wait解法 给定两个单词(beginWord 和 endWord)和一个字典,找到从 beginWord 到 endWord 的最短转换序列的长度。转换需遵循如下规则: 每次转换只能改变一个字母。 转换过程中的中间单词必须是字典中的单词。 说明: 如果不存在这样的转换序列,返回 0。 所有单词具有相同的长度。 所有单词只由小写字母组成。 字典中不存在重复的单词。 你可以假设 beg...

Heorin X的博客 301

[leetcode] word ladder II

http://leetcode.com/onlinejudge#question_126 Q: Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: Only one let...

渴死的火烈鸟 8922

LeetCode_Array_126. Word Ladder II单词接龙II(C++)【双向BFS构图+DFS寻找路径】

1,题目描述 英文描述 Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: Only one letter can be changed at a time Each transformed word must exist in the wo...

&再见萤火虫&的博客 749

126. Word Ladder II(js)

126.Word Ladder II Given two words (beginWordandendWord), and a dictionary's word list, find all shortest transformation sequence(s) frombeginWordtoendWord, such that: Only one letter can be...

weixin_30344995的博客 121

Word Ladder II 相邻字符串接龙 BFS

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that: Only one letter can be changed at a timeEach intermediate word must exi

兔子哥哥的博客 1609

【LeetCode】#126单词接龙II(Word Ladder II)

【LeetCode】#126单词接龙II(Word Ladder II) 题目描述 给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则: 1.每次转换只能改变一个字母。 2.转换过程中的中间单词必须是字典中的单词。 说明: 1.如果不存在这样的转换序列,返回一个空列表。 2.所有...

weixin_43858604的博客 427

126. Word Ladder II

Given two words (beginWordandendWord), and a dictionary's word list, find all shortest transformation sequence(s) frombeginWordtoendWord, such that: Only one letter can be changed at a time Eac...

万里归来少年心 473

126. 单词接龙 II BFS

力扣反图典型题目,单词接龙2

yu_duan_hun的博客 386

(每日一练C++)126. 单词接龙 II

按字典wordList 完成从单词 beginWord 到单词 endWord 转化,一个表示此过程的 转换序列 是形式上像 beginWord -> s1 -> s2 -> ... -> sk 这样的单词序列,并满足: 每对相邻的单词之间仅有单个字母不同。 转换过程中的每个单词 si(1 <= i <= k)必须是字典wordList 中的单词。注意,beginWord 不必是字典 wordList 中的单词。 sk == endWord 给你两个单词 begin..

weixin_39827856的博客 577

[Leetcode][python]Word Ladder/Word Ladder II/单词接龙/单词接龙 II

Word Ladder题目大意给定一个起始字符串和一个目标字符串,现在将起始字符串按照特定的变换规则转换为目标字符串,求最少要进行多少次转换。转换规则为每次只能改变字符串中的一个字符,且每次转换后的字符串都要在给定的字符串集合中。解题思路参考:https://shenjie1993.gitbooks.io/leetcode-python/127%20Word%20Ladder.html 题目在20

蛮三刀酱 1617
上一篇: 【算法】Find the Closest Palindrome 寻找最近的较小回数
下一篇: 【swift】struct与class 的区别
无良剑染
博客等级 码龄11年 3粉丝 65原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值