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

来源:互联网 发布:淘宝客拉人宣传单 编辑:程序博客网 时间:2024/05/16 23:56
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
原创粉丝点击