为什么这个 Lua Dijkstra 算法在某些情况下不起作用?
2019-4-30 14:22:59
收藏:0
阅读:81
评论:0
我正在使用来自此网站的Dijkstra算法代码:https://rosettacode.org/wiki/Dijkstra%27s_algorithm#Lua
不幸的是,它不适用于当前的边缘表。
我已经确定,当我删除从35 -> 36的连接时,问题会消失,但这并不能解决问题。
-- 图的定义
local edges = {
[34] = {[35] = 1,[37] = 1,},
[35] = {[34] = 1,[36] = 1,[46] = 1,},
[36] = {[35] = 1,[37] = 1,},
[37] = {[34] = 1,[36] = 1,},
[38] = {[46] = 1,},
[46] = {[35] = 1,[38] = 1,},
}
-- 在声明的边缘相反方向上完整路径
function complete(graph)
for node, edges in pairs(graph) do
for edge, distance in pairs(edges) do
if not graph[edge] then graph[edge] = {} end
graph[edge][node] = distance
end
end
end
-- 从先前节点的表中创建路径字符串
function follow (trail, destination)
local path, nextStep = destination, trail[destination]
while nextStep do
path = nextStep .. " " .. path
nextStep = trail[nextStep]
end
return path
end
-- 找到当前节点和目标节点之间的最短路径
function dijkstra (graph, current, destination, directed)
if not directed then complete(graph) end
local unvisited, distanceTo, trail = {}, {}, {}
local nearest, nextNode, tentative
for node, edgeDists in pairs(graph) do
if node == current then
distanceTo[node] = 0
trail[current] = false
else
distanceTo[node] = math.huge
unvisited[node] = true
end
end
repeat
nearest = math.huge
for neighbour, pathDist in pairs(graph[current]) do
if unvisited[neighbour] then
tentative = distanceTo[current] + pathDist
if tentative < distanceTo[neighbour] then
distanceTo[neighbour] = tentative
trail[neighbour] = current
end
if tentative < nearest then
nearest = tentative
nextNode = neighbour
end
end
end
unvisited[current] = false
current = nextNode
until unvisited[destination] == false or nearest == math.huge
return distanceTo[destination], follow(trail, destination)
end
-- 主要过程
print(“有向:”,dijkstra(edges,34,38,true))
print(“无向:”,dijkstra(edges,34,38,false))
使用当前边缘表内容,我接收到inf,38的输出,但是当我删除从35到36的连接时,它会给出一个良好的输出 - 3,34 35 46 38
为了更好地理解,我上传了边缘表的图形表示: https://i.imgur.com/FFF22C1.png
正如您所看到的,当我们从34开始 -> 35 -> 46 -> 38 时,路线是正确的,但是正如我所说,仅在35到36的连接不存在时才有效。
为什么它在我的代码中显示的情况下不起作用?
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
