最小生成树-Prim算法 java代码实现

 /* *日期:2010-04-18 11:37 *开发者:heroyan *联系方式:[email protected] *功能:无向图最小生成树Prim算法实现案例 */ import java.util.Scanner; import java.util.Arrays; import java.util.ArrayList; public class SpanningTree{ private static int MAX = 100; private double cost[][] = new double[MAX][MAX]; private ArrayList<Edge> edge = new ArrayList<Edge>(); private int[] near = new int[MAX]; private static double INFINITY = 99999999.99;//定义无穷大 private double mincost = 0.0;//最小成本 private int n;//结点个数 public SpanningTree(){} public static void main(String args[]){ SpanningTree sp = new SpanningTree(); sp.init(); sp.prim(); sp.print(); } //初始化 public void init(){ Scanner scan = new Scanner(System.in); int p,q,w; System.out.println("spanning tree begin!Input the node number:"); n = scan.nextInt(); //二维数组的填充要注意 for(int i = 0; i < MAX; ++i){ Arrays.fill(cost[i],INFINITY); } System.out.println("Input the graph(-1,-1,-1 to exit)"); while(true){ p = scan.nextInt(); q = scan.nextInt(); w = scan.nextInt(); if(p < 0 || q < 0 || w < 0){ break; } cost[p][q] = w; cost[q][p] = w; } Edge tmp = getMinCostEdge(); edge.add(tmp); p = tmp.start; q = tmp.end; mincost = cost[p][q]; for(int i = 1; i <= n; ++i){ if(cost[i][p] < cost[i][q]){ near[i] = p; }else{ near[i] = q; } } near[p] = near[q] = 0; } //寻找最小成本的边 public Edge getMinCostEdge(){ Edge tmp = new Edge(); double min = INFINITY; for(int i = 1; i < n; ++i){ for(int j = i+1; j <= n; ++j){ if(cost[i][j] < min){ min = cost[i][j]; tmp.start = i; tmp.end = j; } } } //System.out.println(min); return tmp; } //prim算法主体 public void prim(){ //找剩下的n-2条边 for(int i = 2; i < n; ++i){ double min = INFINITY; Edge tmp = new Edge(); for(int j = 1; j <= n; ++j){ if(near[j] != 0 && cost[j][near[j]] < min){ tmp.start = j; tmp.end = near[j]; min = cost[j][near[j]]; } } mincost += cost[tmp.start][tmp.end]; edge.add(tmp); near[tmp.start] = 0; for(int k = 1; k <= n; ++k){ if(near[k] != 0 && cost[k][near[k]] > cost[k][tmp.start]){ near[k] = tmp.start; } } } if(mincost >= INFINITY){ System.out.println("no spanning tree"); } } //打印结果 public void print(){ for(int i = 0; i < edge.size(); ++i){ Edge e = edge.get(i); System.out.println("the " + (i+1) + "th edge:" + e.start + "---" + e.end); } } } class Edge { public int start;//始边 public int end;//终边 }

你可能感兴趣的:(java,算法,tree,Graph,Class,input)