[英]How to find all nodes distance k away from each other in directed graph (exploring every edge in a graph)?
[英]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.