我正在使用Prim 算法和 Java 中的 PriorityQueue来研究最小生成树。但是,我弄错了总重量(树的最小重量)。
我是否误解了总重量背后的概念,还是我的代码有问题?
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;
}