普莱姆算法生成最小代价树---java代码

public class MinWeightTree {
public static String[] pointName;
public static int[][] pointDistance;

public static List<Integer[]> result = new ArrayList<Integer[]>();
public static Set<Integer> pointSet = new TreeSet<Integer>();

public static void main(String[] args) {
treeRun();
for (Integer[] sult : result) {
System.out.println("从:" + pointName[sult[0]] + "到:" + pointName[sult[1]]);
}
System.out.println(111);
}


private static void treeRun() {
pointName = new String[]{"山东", "河北", "广西", "山西", "北京", "上海", "内蒙古"};
initPointDistance();
comput();

}

/**
* 过程:
* 1. 从pointName随机挑选一个point作为firstPoint_index,并添加到pointSet中
* 2. 在pointName找出离firstPoint_index最近的point,作为minWeightIndex_firstPointIndex,并添加到pointSet
* 3. [firstPoint_index, minWeightIndex_firstPointIndex]添加到result

* 4. 在pointName中找出离pointSet最近的point,作为:point_index。在pointSet中离point_index最近的point_index2。
* 5. pointSet.add(point_index)。 result.add([point_index2, point_index]);
* 6.重复:4 5 直到pointSet和pointName一样大。
*/
public static void comput() {
if ( pointSet.size() == 0 ) {
int firstPoint = new Random().nextInt(pointName.length);
pointSet.add(firstPoint);
int minWeightIndex_pointIndex = ArrayUtil.getMinIndexFromArray(pointDistance[firstPoint]);
pointSet.add(minWeightIndex_pointIndex);
Integer[] trun1 = new Integer[]{firstPoint, minWeightIndex_pointIndex};
result.add(trun1);
comput();
}else if (pointSet.size() == pointName.length){

}else{
int[] distances = new int[pointSet.size()];
Integer[][] minWeightIndex = new Integer[pointSet.size()][2];
int i = 0;
for (Integer point : pointSet) {
int minWeightIndex_pointIndex_tmp = ArrayUtil.getMinIndexFromArray(pointDistance[point], pointSet);
distances[i] = pointDistance[point][minWeightIndex_pointIndex_tmp];
minWeightIndex[i] = new Integer[]{point, minWeightIndex_pointIndex_tmp};
i ++;
}
int pointSet_Min_index = ArrayUtil.getMinIndexFromArray(distances);
for (int j2 = 0; j2 < pointSet.size(); j2++) {
if ( j2 == pointSet_Min_index ) {
result.add(minWeightIndex[j2]);
pointSet.add(minWeightIndex[j2][1]);
}
}
comput();
}

}




public static void initPointDistance() {
pointDistance = new int[pointName.length][pointName.length];
for (int i = 0; i < pointName.length; i++) {
for (int j = 0; j < pointName.length; j++) {
pointDistance[i][j] = Math.abs(i - j);//point在1维上,在2维上使用2维的方法。
}
}
}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值