[英]Dijkstra's algorithm in Java source and target
我正在嘗試使用Dijkstra的算法來找到圖中兩個節點之間的最短路徑。
找到源與目標之間的最短路徑后,如何對以下代碼停止計算?
public void calculate(Vertex source){
// Algo:
// 1. Take the unvisited node with minimum weight.
// 2. Visit all its neighbours.
// 3. Update the distances for all the neighbours (In the Priority Queue).
// Repeat the process till all the connected nodes are visited.
source.minDistance = 0;
PriorityQueue<Vertex> queue = new PriorityQueue<Vertex>();
queue.add(source);
while(!queue.isEmpty()){
Vertex u = queue.poll();
for(Edge neighbour:u.neighbours){
Double newDist = u.minDistance+neighbour.weight;
if(neighbour.target.minDistance>newDist){
// Remove the node from the queue to update the distance value.
queue.remove(neighbour.target);
neighbour.target.minDistance = newDist;
// Take the path visited till now and add the new node.s
neighbour.target.path = new LinkedList<Vertex>(u.path);
neighbour.target.path.add(u);
//Reenter the node with new distance.
queue.add(neighbour.target);
}
}
}
}
當找到源和目標之間的最短路徑時,我應該對以下代碼做什么以停止計算
您不能在中間“中斷”,因為在算法完成之前,您無法確定是否沒有比您已經找到的路徑更短的路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.