import java.util.Arrays;
class MST{
int startVertex;
int endVertex;
int length;
boolean sure = false;
public MST(int startVertex, int endVertex, int length) {
this.startVertex = startVertex;
this.endVertex = endVertex;
this.length = length;
}
@Override
public String toString() {
return "(" + startVertex +
"," + endVertex +
"," + length +
')';
}
}
public class Main {
//矩阵阶数
static int matrixOrder = 6;
//MST
static MST[] msts = new MST[matrixOrder - 1];
//无穷距离
static int MD = 999;
//邻接矩阵
static int[][] arcs = {
{0, 10, MD, MD, 19, 21},
{10, 0, 5, 6, MD, 11},
{MD, 5, 0, 6, MD, MD},
{MD, 6, 6, 0, 18, 14},
{19, MD, MD, 18, 0, 33},
{21, 11, MD, 14, 33, 0 }} ;
static boolean isOver(){
for(int i = 0; i < msts.length; i++){
if(!msts[i].sure){
return false;
}
}
return true;
}
static int findMinLengthVertex(){
int minLength = MD;
int minIndex = matrixOrder;
for(int i = 0; i < msts.length; i++){
if(!msts[i].sure && msts[i].length <= minLength){
minLength = msts[i].length;
minIndex = i;
}
}
msts[minIndex].sure = true;
int minVertexIndex = msts[minIndex].endVertex;
return minVertexIndex;
}
static void prim(){
//初始化msts
for(int i = 0; i < msts.length; i++){
MST mst = new MST(0, i + 1, arcs[0][i+1]);
msts[i] = mst;
}
//算法开始
while(true){
if(isOver())
break;
int minLengthVertex = findMinLengthVertex();
for(int i = 0; i < msts.length; i++){
if(!msts[i].sure && msts[i].length > arcs[minLengthVertex][msts[i].endVertex]){
msts[i].startVertex = minLengthVertex;
msts[i].length = arcs[minLengthVertex][msts[i].endVertex];
}
}
}
}
public static void main(String[] args) {
prim();
System.out.println(Arrays.toString(msts));
}
}