import java.util.*;
class PrimAlgorithm {
private static final int INF = Integer.MAX_VALUE;
public void primMST(int[][] graph) {
int vertices = graph.length;
int[] parent = new int[vertices]; // 用于存储最小生成树的父节点
int[] key = new int[vertices]; // 用于存储顶点的权值
boolean[] mstSet = new boolean[vertices]; // 用于标记顶点是否已经加入最小生成树
// 初始化key数组为无穷大,mstSet数组为false
Arrays.fill(key, INF);
Arrays.fill(mstSet, false);
// 将第一个顶点作为起始点
key[0] = 0;
parent[0] = -1;
for (int i = 0; i < vertices - 1; i++) {
int minKey = minKeyIndex(key, mstSet);
mstSet[minKey] = true;
// 更新与选中顶点相邻的顶点的权值和父节点
for (int j = 0; j < vertices; j++) {
if (graph[minKey][j] != 0 && !mstSet[j] && graph[minKey][j] < key[j]) {
parent[j] = minKey;
key[j] = graph[minKey][j];
}
}
}
printMST(parent, graph);
}
private int minKeyIndex(int[] key, boolean[] mstSet) {
int min = INF;
int minIndex = -1;
for (int i = 0; i < key.length; i++) {
if (!mstSet[i] && key[i] < min) {
min = key[i];
minIndex = i;
}
}
return minIndex;
}
private void printMST(int[] parent, int[][] graph) {
System.out.println("Edge \tWeight");
for (int i = 1; i < graph.length; i++) {
System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]);
}
}
public static void main(String[] args) {
int[][] graph = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
PrimAlgorithm prim = new PrimAlgorithm();
prim.primMST(graph);
}
}
标签:Prim,parent,int,graph,最小,minKey,算法,key,mstSet
From: https://www.cnblogs.com/ukzq/p/17644424.html