带邻接矩阵的Dijkstra算法

时间:2019-05-26 07:14:23

标签: julia

我正在尝试从here实现以下代码,但无法正常工作。

我想要的是从源到所有节点以及前任节点的最短路径距离。另外,我希望图的输入为包含所有边缘权重的邻接矩阵。

我试图使其仅在一个函数中起作用,所以我必须重写它。如果我是对的,原始代码将调用其他函数(例如,来自graph.jl)。

我不太了解如何重写调用adj()函数的for循环。

此外,我不确定目前输入的代码是否正确。

function dijkstra(graph, source)
    node_size = size(graph, 1)
    dist = ones(Float64, node_size) * Inf
    dist[source] = 0.0
    Q = Set{Int64}()  # visited nodes
    T = Set{Int64}(1:node_size)  # unvisited nodes
    pred = ones(Int64, node_size) * -1
    while condition(T)
        # node selection
        untraversed_nodes = [(d, k) for (k, d) in enumerate(dist) if k in T]
        if minimum(untraversed_nodes)[1] == Inf
            break # Break if remaining nodes are disconnected
        end
        node_ind = untraversed_nodes[argmin(untraversed_nodes)][2]
        push!(Q, node_ind)
        delete!(T, node_ind)
        # distance update
        curr_node = graph.nodes[node_ind]
        for (neigh, edge) in adj(graph, curr_node)
            t_ind = neigh.index
            weight = edge.cost
            if dist[t_ind] > dist[node_ind] + weight
                dist[t_ind] = dist[node_ind] + weight
                pred[t_ind] = node_ind
            end
        end
    end
    return dist, pred
end

因此,如果我尝试使用以下矩阵

A = [0 2 1 4 5 1; 1 0 4 2 3 4; 2 1 0 1 2 4; 3 5 2 0 3 3; 2 4 3 4 0 1; 3 4 7 3 1 0] 

和源2我想获得向量dist中的距离和向量pred中的前任。

现在我要得到

错误:数组类型没有字段节点

  

Stacktrace:[1] getproperty(:: Any,:: Symbol)at。\ sysimg.jl:18

我想我还要重写一点。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

假设graph[i,j]是从ij的路径长度(您的图形直接指向您的数据),并且它是一个{否定条目,其中Matrix表示从0i没有任何边,代码的最小重写应类似于:

j

(我尚未对其进行广泛的测试,因此请报告是否发现任何错误)