问题描述
题目描述:某物流派送员p,需要给a、b、c、d4个快递点派送包裹,请问派送员需要选择什么的路线,才能完成最短路程的派送。假设如图派送员的起点坐标(0,0),派送路线只能沿着图中的方格边行驶,每个小格都是正方形,且边长为1,如p到d的距离就是4。随机输入n个派送点坐标,求输出最短派送路线值
回溯法搜寻排列树
import java.util.Scanner;
public class ToutiaoNewsPuller{
static int num = 4;
static Point[] points = new Point[num];
static int min = Integer.MAX_VALUE;//将最小距离初始化为最大值
//对点进行排序
public static int permutation(int k){
if(k == num){
Point start = new Point(0,0);//每次都要初始化为0点,不然下面出问题
int sum = output(start);
if(sum<min){
min = sum;
}
return min;
}else{
for(int t = k; t < num; t ++){
swap(t,k);
permutation(k+1);
swap(t,k);
}
}
return min;
}
//调换两点位置
public static void swap(int k, int j){
Point p = points[k];
points[k] = points[j];
points[j] = p;
}
//计算每一种排序距离
public static int output(Point start) {
int sum = 0;
for (int k = 0; k < num; k++) {
sum = points[k].getLength(start) + sum;
start = points[k];
}
return sum;
}
public static void main(String[] args) {
System.out.println("Please enter the points");
Scanner in = new Scanner(System.in);
for(int i = 0; i < num; i ++){
String[] str = in.nextLine().trim().split(",");
points[i] = new Point(Integer.parseInt(str[0]),Integer.parseInt(str[1]));
}
System.out.println(permutation(0));
Main m = new Main();
System.out.println(m.caculate(new Point(0,0),points,0,0));
}
}