为什么这个 Lua Dijkstra 算法在某些情况下不起作用?

我正在使用来自此网站的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,3438true))
print(“无向:”,dijkstra(edges,3438false))

使用当前边缘表内容,我接收到inf,38的输出,但是当我删除从35到36的连接时,它会给出一个良好的输出 - 3,34 35 46 38

为了更好地理解,我上传了边缘表的图形表示: https://i.imgur.com/FFF22C1.png

正如您所看到的,当我们从34开始 -> 35 -> 46 -> 38 时,路线是正确的,但是正如我所说,仅在35到36的连接不存在时才有效。

为什么它在我的代码中显示的情况下不起作用?

点赞