Prim算法实现

//输入是指定的生成树的根结点,和一个矩阵表示的完全无向图
public static Object [] Prim(int u0,double graph[][]) throws Exception{ for(int i =0;i<graph.length;i++){ if(graph[i].length!=graph.length){ throw new Exception("input graph isn't a complete graph"); } } int numAtts=graph.length; int treeNode[][]=new int[numAtts][2]; double weight[]=new double[numAtts]; for(int b=0;b<treeNode.length;b++){ graph[b][u0]=Double.NaN; treeNode[b][0]=Integer.MAX_VALUE; //初始化为Integer的最大值.如果为最大值表示当前结点为空 } treeNode[0][0]=u0; treeNode[0][1]=-1;// for(int a=0;a<treeNode.length-1;a++){ double []result =findMax(treeNode,graph); int largestIndex=(int)result[0]; weight[a+1]=result[1]; treeNode[a+1][0]=largestIndex; treeNode[a+1][1]=(int)result[2]; /* for(int b=0;b<treeNode.length;b++){ graph[b][largestIndex]=Double.NaN; } graph[largestIndex][treeNode[a][0]]=Double.NaN; */ } printArray(treeNode); return new Object[]{treeNode,weight}; } /** * 根据输入的树的长度及内里里面的内容,先找出不在树中的点 * 然后找出一顶点在树中 的另外一个顶点不在树中的权值最大的边 * @param node * @param graph * @return 一个1维数组[int,double,int],数组的索引0是权值最大的边的不在树中的结点,索引1是最大权重,索引2是在树中的结点 */ private static double[] findMax(int treeNode[][],double [][] graph){ //用来存放找出的边的结点及权重,这里也就是信息熵 double tempValue=Integer.MIN_VALUE; int tempIndex=Integer.MIN_VALUE; int temp=Integer.MIN_VALUE;//temp是所找出结点的根结点 //声明并初始化为true boolean outSideOfTree[] = new boolean[treeNode.length]; for(int i = 0;i<outSideOfTree.length;i++){ outSideOfTree[i] =true; } //下面这个for循环找出哪个结点不在树中 for (int k=0 ;k<treeNode.length;k++){ if(treeNode[k][0]!=Integer.MAX_VALUE ){ outSideOfTree[treeNode[k][0]]=false; } } //找一个结点在树里面,一个结点在树外面权值最大的边 for(int j=0;j<treeNode.length;j++){ if(treeNode[j][0]!=Integer.MAX_VALUE){ //对于每个树中存在的结点值做下面操作 for(int k=0;k<outSideOfTree.length;k++){ if(outSideOfTree[k]){ //与不在树中的结点分别比较,找出适合的结点的Index //找出最大的边 if(graph[treeNode[j][0]][k]>tempValue){ tempValue = graph[treeNode[j][0]][k]; tempIndex= k; temp = treeNode[j][0]; } } } } } return new double []{tempIndex,tempValue,temp}; }

 

转载于:https://www.cnblogs.com/alexmercer/p/4657116.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值