2013-05-25 56 views
2

我正在使用帶有Java中的PriorityQueue的Prim's Algorithm使用最小生成樹。但是,我得到的總重量(樹的最小重量)是錯誤的。Prim的算法

我誤解總重量背後的概念,或者是有一些問題,我的代碼?

public int getMinSpanningTree(Graph g) { 
    int[][] matrix = g.getEdgeMatrix(); 
    int totalVertices = g.getNumberOfVertices(); 
    boolean[] visit = new boolean[totalVertices]; 
    int visitNum = 1; 
    int totalWeight = 0; 
    PriorityQueue<PriorityVertex> queue = new PriorityQueue<PriorityVertex>(); 

    //FIRST ITERATION 
    visit[0] = true; 
    for (int i = 0; i < totalVertices; i++) { 
     if(matrix[0][i] > 0) { 
      PriorityVertex temp = new PriorityVertex(i, g.getWeight(0,i)); 
      queue.add(temp); 
     } 
    } 

    while (visitNum < totalVertices) { 
     PriorityVertex temp = queue.poll(); 
     visit[temp.vertex] = true; 
     visitNum++; 
     totalWeight = temp.priority + totalWeight; 
     //RUN NEIGHBOUR VERTICES 
     for (int k = 0; k < totalVertices; k++) { 
      if(matrix[temp.vertex][k] > 0 && visit[k] == false) { 
       PriorityVertex vertex = new PriorityVertex(k, g.getWeight(temp.vertex, k)); 
       queue.add(vertex); 
      } 
     } 
    } 
    return totalWeight; 
} 

回答

2

問題是你不能從隊列中移除頂點的所有實例=>同一個頂點可以多次添加到結果中。

假設下圖:

weight(0,1) = 1 
weight(0,2) = 2 
weight(1,2) = 3 
weight(1,3) = 4 
weight(2,3) = 5 

的 「第一迭代」 後,將隊列包含PriorityVertex(1,1),PriortyVertex(2,2)。而週期的

迭代:

1) removed: PriorityVertex(1, 1) - edge (0,1) 
    added: PriorityVerterx(2, 3) and PriorityVertex(3, 4) 
    queue: PriorityVertex(2, 2), PriorityVertex(2, 3), PriorityVertex(3, 4) 

2) removed: PriorityVertex(2, 2) - edge (0,2) 
    added: PriorityVertex(3, 5) 
    queue: PriorityVertex(2, 3), PriorityVertex(3, 4), PriorityVertex(3, 5) 

3) removed: PriorityVertex(2, 3) - edge (1,2), cycle in the result!