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

Golang | Leetcode Golang题解之第127题单词接龙

题目:

题解:

func ladderLength(beginWord string, endWord string, wordList []string) int {wordId := map[string]int{}graph := [][]int{}addWord := func(word string) int {id, has := wordId[word]if !has {id = len(wordId)wordId[word] = idgraph = append(graph, []int{})}return id}addEdge := func(word string) int {id1 := addWord(word)s := []byte(word)for i, b := range s {s[i] = '*'id2 := addWord(string(s))graph[id1] = append(graph[id1], id2)graph[id2] = append(graph[id2], id1)s[i] = b}return id1}for _, word := range wordList {addEdge(word)}beginId := addEdge(beginWord)endId, has := wordId[endWord]if !has {return 0}const inf int = math.MaxInt64distBegin := make([]int, len(wordId))for i := range distBegin {distBegin[i] = inf}distBegin[beginId] = 0queueBegin := []int{beginId}distEnd := make([]int, len(wordId))for i := range distEnd {distEnd[i] = inf}distEnd[endId] = 0queueEnd := []int{endId}for len(queueBegin) > 0 && len(queueEnd) > 0 {q := queueBeginqueueBegin = nilfor _, v := range q {if distEnd[v] < inf {return (distBegin[v]+distEnd[v])/2 + 1}for _, w := range graph[v] {if distBegin[w] == inf {distBegin[w] = distBegin[v] + 1queueBegin = append(queueBegin, w)}}}q = queueEndqueueEnd = nilfor _, v := range q {if distBegin[v] < inf {return (distBegin[v]+distEnd[v])/2 + 1}for _, w := range graph[v] {if distEnd[w] == inf {distEnd[w] = distEnd[v] + 1queueEnd = append(queueEnd, w)}}}}return 0
}
http://www.lryc.cn/news/361184.html

相关文章:

  • 微服务中feign远程调用相关的各种超时问题
  • springboot整合chatgpt,并且让其可以记录上下文
  • CTP前端:解码数字世界的魔法师
  • rabbitmq的交换机类型以及他们的区别
  • 理解不同层的表示(layer representations)
  • 原生js访问http获取数据的方法
  • Windows 2000 Server:安全配置终极指南
  • 基于 FastAI 文本迁移学习的情感分类(93%+Accuracy)
  • 集成Google Authenticator实现多因素认证(MFA)
  • 网关(Gateway)- 自定义过滤器工厂
  • HTML静态网页成品作业(HTML+CSS)—— 香奈儿香水介绍网页(1个页面)
  • C++11 lambda表达式和包装器
  • 3. MySQL 数据表的基本操作
  • Linux命令篇(一):文件管理部分
  • IP协议1.0
  • 源码编译安装LNMP
  • 安装Chrome扩展程序来 一键禁用页面上的所有动画和过渡。有那些扩展程序推荐一下
  • 读人工智能时代与人类未来笔记19_读后总结与感想兼导读
  • 个人影响力
  • OBS实现多路并发推流
  • JDK环境配置、安装
  • 莱富康压缩机的选型软件介绍
  • Pr 2024下载安装,Adobe Premiere专业视频编辑软件安装包获取!
  • MySQL事务与MVCC
  • 【数据结构】链式二叉树详解
  • PHP面向对象编程总结
  • linux中的“->“符号
  • MySql 数据类型选择与优化
  • HTML静态网页成品作业(HTML+CSS)——家乡常德介绍网页(1个页面)
  • 【ARMv7-A】——CP15 协处理器