如何查找并保存特定节点到图表中所有其他节点的距离。请注意,图表是非循环的。
这是我开始使用的代码。我传递一个顶点,访问过的数组,两个节点之间的距离矩阵,最初设置为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
}
答案 0 :(得分:0)
我假设你的意思是有向无环图。可以使用在O(E + VlogV)中运行的Dijkstra。
答案 1 :(得分:0)
由于该图是非循环的,因此不需要djikstras。相反,拓扑排序可用于| V + E |的运行时。
答案 2 :(得分:-1)
如果您正在寻找所有配对最短路径问题,可以使用Floyd-Warshall Algorithm。