[英]Compute Paths - Dijkstra's algorithm
我看到了dijkstra算法的實現,但我不太理解這段代碼的某些部分:
public static void computePaths(Vertex source) {
source.minDistance = 0;
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
while (!vertexQueue.isEmpty()) {
Vertex u = vertexQueue.poll();
// Visit each edge exiting u
for (Edge e : u.adjacencies) {
Vertex v = e.target;
double distanceThroughU = u.minDistance + e.getweight();
if (distanceThroughU < v.minDistance) {
vertexQueue.remove(v); //How can I remove if I didn't add it first, and why do I need to remove?
v.minDistance = distanceThroughU;
v.previous = u;
vertexQueue.add(v); //Why is it add again?
}
}
}
}
我了解了dijkstra的算法,所以我了解一般的邏輯,但是當我看到此實現時,有幾件事我不明白為什么要這么做。 有人可以解釋一下嗎? 特別是在我有評論的地方!
更新節點v的信息
您想要更新存儲在優先級隊列中的節點v的信息,因為找到了一條較短的路徑。
如果該節點存在於優先級隊列中, 則 Remove()函數將其刪除。
之后,您更新信息,然后將其與更新后的信息一起再次添加。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.