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

/*

*日期:2010-04-18 11:37

*开发者:heroyan

*联系方式:zndxysf@126.com

*功能:无向图最小生成树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 = new ArrayList();

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值