public class Prime { public static void main(String[] args) { //路径矩阵 int arcs[][] = {{-1,6,1,5,-1,-1},{6,-1,5,-1,3,-1},{1,5,-1,5,6,4},{5,-1,5,-1,-1,2},{-1,3,6,-1,-1,6},{-1,-1,4,2,6,-1}}; //[i][0]保存i到那个顶点 [i][1]保存这两个顶点之间的距离,如果为0则代表顶点i已经加入到了最小生成树里,如果为-1则这两个顶点之间不存在直接相连的边 int closedge[][] = new int[arcs.length][2]; int start = 0;//初始化顶点为0 closedge[start][1] = 0;//顶点0已经被加入到最小生成树集合U for(int i=0;i<arcs.length;i++){//初始化其他顶点到顶点0的状态 if(i!=start){ closedge[i][0] = start; //顶点i到顶点start(0) closedge[i][1] = arcs[start][i]; //顶点i和顶点0之间的距离 } } for(int i=0;i<arcs.length-1;i++){ int k = 0; int min = Integer.MAX_VALUE; for(int j=0;j<arcs.length;j++){//循环closedge 找出距离最短的那一条 if(closedge[j][1] < min && closedge[j][1] != 0 && closedge[j][1] != -1){ min = closedge[j][1]; k = j;//记录下来是到哪个顶点最小 } } closedge[k][1] = 0;//然后将该顶点加入到集合U中 System.out.println(closedge[k][0]+1 +"->" + (k+1));//输出从那条边 for(int a=0;a<arcs.length;a++){ //以下一个顶点为起点 重新计算距离 if(arcs[k][a]!=-1&& closedge[a][1] !=0){ closedge[a][0] = k; closedge[a][1] = arcs[k][a]; } } } } }