1. 程式人生 > >ali內推——圖的深度搜索

ali內推——圖的深度搜索

如圖,某物流派送員p,需要給a、b、c、d4個快遞點派送包裹,請問派送員需要選擇什麼的路線,才能完成最短路程的派送。假設如圖派送員的起點座標(0,0),派送路線只能沿著圖中的方格邊行駛,每個小格都是正方形,且邊長為1,如p到d的距離就是4。隨機輸入n個派送點座標,求輸出最短派送路線值(從起點開始完成n個點派送並回到起始點的距離)。 輸入 4 2,2 2,8 4,4 7,2 輸出30 輸入 2,2 2,8 6,6 輸出28

 

 注意:

  1. 最後要回到原點
  2. 圖的深度遍歷
import java.util.Scanner;

/**
 * Copyright(C) 2018-2018
 * Author: wanhaoran
 * Date: 2018/7/21 17:11
 */
public class Main {
    static int minpath = Integer.MAX_VALUE;

    final static Point START = new Point(0,0);

    public static void caculate(Point start, Point[] points, int sum,int count) {

        for (int i = 0; i < points.length; i++) {
            if (points[i].isVisited == false) {
                points[i].isVisited = true;
                count++;
                sum += start.getLength(points[i]);
                if (count == points.length){
                    sum+=points[i].getLength(START);
                    if (sum<minpath){
                        minpath = sum;
                    }
                }
                caculate(points[i], points, sum,count);
                points[i].isVisited = false;
                count--;
                sum -= start.getLength(points[i]);
            }
        }

    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = Integer.parseInt(scanner.nextLine().trim());
        Point[] points = new Point[num];
        for (int i = 0; i < num; i++) {
            String[] locations = scanner.nextLine().trim().split(",");
            points[i] = new Point(Integer.parseInt(locations[0]), Integer.parseInt(locations[1]));
        }
        caculate(new Point(0,0),points,0,0);
        System.out.println(minpath);
    }
}


class Point {
    int x, y;
    boolean isVisited;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
        this.isVisited = false;
    }

    public int getLength(Point point) {
        return Math.abs(this.x - point.x) + Math.abs(this.y - point.y);
    }
}