[英]Djikstra's Algorithm using Adjacency List and Priority queue in java
我無法理解為什么我的dijkstraShortestPath(int startVertex)函數無法正常工作。 我正在為我的項目使用偽代碼,但是我不明白我在做什么錯。
對於我的算法,只有我的起始頂點顯示。
我也有一個DFS,但是我不確定是否應該在dijkstraShortestPath方法中使用它,如果可以,如何實現它?
我認為我的問題是在“ while循環”中還是在初始化名為“ pq”的優先級隊列的方式中。
鏈接到完整代碼: https : //www.dropbox.com/s/b848b9ts5lrfn01/Graph%20copy.java? dl =0
鏈接到偽代碼: https : //www.dropbox.com/s/tyia0sr3t9r8snf/Dijkstra%27s%20Algorithm%20%281%29.docx? dl =0
鏈接到要求: https : //www.dropbox.com/s/rq8km8rp4jvyxvp/Project%202%20Description-1%20%282%29.docx?dl=0
以下是我的Dijkstra算法的代碼。
public void dijkstraShortestPaths(int startVertex) {
// Initialize VARS and Arrays
int count = 0, start = startVertex;
int[] d;
int[] parent;
d = new int[nVertices];
parent = new int[nVertices];
DistNode u;
// 10000 is MAX/Infinity
for (int i = 0; i < nVertices; i++) {
parent[i] = -1;
d[i] = 10000;
}
// Initialize Start vertex distance to 0
d[startVertex] = 0;
// Setup Priotiry Queue
PriorityQueue<DistNode> pq = new PriorityQueue<DistNode>();
for(int i = 0; i < adjList[start].size(); i++){
pq.add(new DistNode(adjList[start].get(i).destVertex, adjList[start].get(i).weight));
}
System.out.print(pq);
//
while (count < nVertices && !pq.isEmpty()) {
// remove DistNode with d[u] value
u = pq.remove();
count++;
System.out.println("\n\nu.vertex: " + u.vertex);
// for each v in adjList[u] (adjacency list for vertex u)
for(int i = 0; i < adjList[u.vertex].size();i++){
// v
int v = adjList[u.vertex].get(i).destVertex;
System.out.println("v = " + v);
// w(u,v)
int vWt = adjList[u.vertex].get(i).weight;
System.out.println("vWt = " + vWt + "\n");
if((d[u.vertex] + vWt) < d[v]){
d[v] = d[u.vertex] + vWt;
parent[v] = u.vertex;
pq.add(new DistNode(v,d[v]));
}
}
}
printShortestPaths(start, d, parent);
}
您使用PriorityQueue
的問題在於,優先級隊列的內容與數組d
的內容無關; 並聲明:
pq.add(new DistNode(v,d[v]));
應該用頂點v
替換pq
任何DistNode
,否則,您可能會多次訪問相同的頂點。
我不確定PriorityQueue
是否適合該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.