练习题:
蜂巢在坐标(0,0)的位置,有五处花丛,蜜蜂从蜂巢出发,要把五处花丛的花蜜采完再回到蜂巢,最短距离是多少。输入说明:一行输入,10个数分别是五处花丛的坐标(x1,y1,x2,y2,x3,y3,x4,y4,x5,y5)
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
//求最短路径
long td=System.currentTimeMillis();
int[][] a = {{0, 0}, {1, 1}, {2, 1}, {3, 1}, {4, 1}, {6, 2}};
Test t = new Test();
System.out.println((t.getMin(t.sum(a))));
//保留4位小数
System.out.println(new BigDecimal(t.getMin(t.sum(a))).setScale(4,BigDecimal.ROUND_HALF_DOWN));
System.out.println("耗时:"+(System.currentTimeMillis()-td));
}
//计算所有可能出现的路径
private double[] sum(int[][] b) {
double[] result = new double[b.length];
double x0=0;
double x=0;
for (int j = 0; j < b.length; j++) {
for (int i = 0; i < b.length - 1; i++) {
//求得路径
if (i == 0&&j==1) {
x0 = Math.sqrt(Math.pow(b[j][0] - b[i][0], 2) + Math.pow(b[j][1] - b[i][1], 2));
} else {
x+= Math.sqrt(Math.pow(b[i][0] - b[i + 1][0], 2) + Math.pow(b[i][1] - b[i + 1][1], 2));
}
}
result[j] = x0 + x;
}
return result;
}
//计算最小路径
private double getMin(double[] c) {
for (int i = 0; i < c.length-1; i++) {
if (c[i] > c[i + 1]) {
double mm = c[i];
c[i] = c[i + 1];
c[i + 1] = mm;
}
}
return c.length > 0 ? c[0] : 0;
}
}