package com.gxmedu.prim;
import java.util.Arrays;
public class MGraph {
int vertexNum;
char[] data;
int[][] edgeWeight;
public MGraph(int vertexNum){
this.vertexNum = vertexNum;
data = new char[vertexNum];
edgeWeight = new int[vertexNum][vertexNum];
}
public void fillGraph(char[] data,int[][] edgeWeight){
this.data = data;
this.edgeWeight = edgeWeight;
}
public void showGraph(){
for (int i = 0; i < vertexNum ; i++) {
System.out.println(Arrays.toString(edgeWeight[i]));
}
}
}
package com.gxmedu.prim;
public class MinimumCostSpanningTree {
public static void main(String[] args) {
char[] data = new char[]{'A','B','C','D','E','F','G'};
int vertexNum = data.length;
int[][] weight = new int[][]{
{-1,5,7,-1,-1,-1,2},
{5,-1,-1,9,-1,-1,3},
{7,-1,-1,-1,8,-1,-1},
{-1,9,-1,-1,-1,4,-1},
{-1,-1,8,-1,-1,5,4},
{-1,-1,-1,4,5,-1,6},
{2,3,-1,-1,4,6,-1}
};
MGraph g1 = new MGraph(vertexNum);
g1.fillGraph(data,weight);
MinimumCostSpanningTree mst = new MinimumCostSpanningTree();
mst.prim(g1,0);
}
public void prim(MGraph g,int origin){
boolean[] isVisited = new boolean[g.vertexNum];
isVisited[origin] = true;
for (int i = 1; i < g.vertexNum; i++) {
int minWeight = -1;
int bestVertex1 = -1;
int bestVertex2 = -1;
for (int j = 0; j < g.vertexNum; j++) {
if(!isVisited[j]){
continue;
}
for (int k = 0; k < g.vertexNum; k++) {
if(isVisited[k] || g.edgeWeight[j][k] == -1){
continue;
}
if(g.edgeWeight[j][k] < minWeight || minWeight == -1){
minWeight = g.edgeWeight[j][k];
bestVertex1 = j;
bestVertex2 = k;
}
}
}
isVisited[bestVertex2] = true;
System.out.printf("此轮连接%c->%c,权值为%d\n",g.data[bestVertex1],g.data[bestVertex2],g.edgeWeight[bestVertex1][bestVertex2]);
}
}
}