繁体   English   中英

在加权图中查找从节点到所有其他节点的距离

[英]Find distance from node to all other nodes in a weighted graph

如何找到并保存从特定节点到图中所有其他节点的距离。 请注意,图是无环的。

这是我开始的代码。 我传递了一个顶点、访问过的数组、两个节点之间的距离矩阵,最初设置为 0,
和 dist 应该跟踪当前节点与根节点之间的距离
我给了一个目标。
我使用 DFS,每次我去下一个节点时,我都会将它们之间的距离添加到前一个
距离并将其作为参数传递给下一个连接(如果存在)。
请帮我完成它。

 void DFSUtil(int v,boolean visited[],ArrayList<ArrayList<Integer>> distanceMatrix,int dist,int targ)
    {
        // Mark the current node as visited and print it
        visited[v]=true;
        System.out.print(v+" ");


        // Recur for all the vertices adjacent to this vertex
        Iterator<Integer> i = adj[v].listIterator();

        while (i.hasNext())
        {
            int n = i.next();

            if (!visited[n]){
                /* dist += distanceMatrix.get(v).get(n);
                System.out.println("cur:"+v+" next:"+n+"\ndistMatrix:"+distanceMatrix.get(v).get(n)+"dist:"+dist);

                distanceMatrix.get(targ).set(n,dist);
                distanceMatrix.get(n).set(targ,dist);
                System.out.println(distanceMatrix);
                System.out.println();*/
                DFSUtil(n, visited,distanceMatrix,dist,targ);
            }
        }
        //remove dist from root to this node
    }

我假设您的意思是有向无环图。 可以使用在 O(E + VlogV) 中运行的 Dijkstra。

您不需要 djikstras,因为该图是无环的。 相反,拓扑排序可用于 |V + E| 的运行时。

如果您正在寻找 All Pair Shortest Path Problem,您可以使用Floyd-Warshall 算法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM