public class Main { static final int MAXVEX =65535; static final int MINVEX =65535; public static void main(String[] args) { MyGrop2 p = new MyGrop2(); new Main().MiniSpanTree(p); } static int Find (int parent [] , int f){ while(parent[f] >0){ f = parent[f]; // 下标 f 指向 parent[f] } return f; } void MiniSpanTree(MyGrop2 G){ int i,n,m; EDGE [] edges = new EDGE[MAXVEX]; for (i=0 ; i<G.srd.length; i++){ edges[i] = new EDGE(); edges[i].begin = G.srd[i][0]; edges[i].end =G. srd[i][1]; edges[i].weight =G.srd[i][2]; } //定义变得数组 int parent [] = new int[MAXVEX];//定义parent来判断便于变是否能形成环 for( i=0 ;i<G.a ;i++ ){ parent[i] = 0; //初始化 } for (i=0 ;i<=G.a ;i++ ){ n = Find(parent ,edges[i].begin); m = Find(parent ,edges[i].end); if(n!=m){ //如果n==m 形成环路 parent[n] = m; //将此节点放入下标为起点parent的数组中,表示此节点存在 System.out.println("("+edges[i].begin+")--"+edges[i].weight+ "--("+edges[i].end+")"); } } } } class EDGE{ int begin; int end; int weight; } class MyGrop2{ final int MINVEX =65535; int a = 9; int srd [][] = { {4,7,7},{2,8,8},{0,1,10},{0,5,11}, {1,8,12},{3,7,16},{1,6,16},{5,6,17},{1,2,18}, {6,7,19},{3,4,20},{3,8,21},{2,3,22},{3,6,24}, {4,5,26}}; }
时间: 2024-10-06 11:16:26