我想用優先級隊列在Java中實現Prim算法。Prim算法優先級隊列
我找不到我的錯誤。 :/我只是認識到隊列沒有正確排序節點。
例如用於圖:
0 4 7 5
4 0 2 3
7 2 0 1
5 3 1 0
它始終以作爲第二個中的節點4。所以它命令隊列像[node1,node4,node2,node3]而不是[node1,node2,node3,node4]。 我對優先級隊列做了什麼錯誤?
問候
public class PrimAlgorithm {
private static int[] par; // parent
private static int[] key; // value
private static int sum;
public static void prim(Graph g){
Node[] nodes = g.getNodes();
key = new int[g.getMatrix().length];
par = new int[g.getMatrix().length];
PriorityQueue<Node> queue = new PriorityQueue<Node>(42, new Comparator<Node>(){
public int compare(Node v1, Node v2){
return Integer.valueOf(key[v1.getId()-1]).compareTo(Integer.valueOf(key[v2.getId()-1]));
for (Node n : nodes) {
int x = n.getId()-1;
key[x] = 1000;
par[x] = 0;
queue.add(n);
}
key[0] = 0;
while(!queue.isEmpty()) {
Node n = queue.poll();
List<Node> neighbours = n.getNeighbors();
for (Node m : neighbours){
if (queue.contains(m) && g.getEdge(n, m).getWeight() !=0 && g.getEdge(n, m).getWeight() < key[m.getId()-1]){
par[m.getId()-1] = n.getId();
key[m.getId()-1] = g.getEdge(n, m).getWeight();
}
}
}
for (int i=0; i < key.length; i++){
sum += key[i];
}
System.out.println("Das Gewicht des minimalen Spannbaumes lautet: " + sum);
System.out.println("Der Spannbaum ergibt sich wie folgt: ");
//fängt ab 1 an sonst, hätten wir immer noch einen Nullknoten
for(int i=0; i <par.length; i++){
System.out.println("Der Vorgänger von Knoten: " + " "+ (i+1) + "-> " + par[i] + " Gewicht "
+ key[i]);
}
}
public static void main(String[] args) {
System.out.println("Prim Algorithmus zu Berechnung des minimalen Spannbaums.");
Graph g = new Graph();
prim(g);
}
}
感謝您的回答。 3號是一個非常好的提示。但是我怎麼知道排隊呢?我讀到可以刪除並重新添加節點,但這不是非常有效 – Loretta
@Loretta斐波那契堆怎麼樣?你可以用較少的計算成本改變它的值 – rpax
@rpax斐波那契堆是org.jgrapht.util中的一個類,我不想使用圖類並通過我自己的方法來實現 – Loretta