import java.util.Scanner;


public class Solution {
	static int sx,sy,hx,hy,n;
	static int[][] map;
	static int ans;
	static boolean visited[];
	static int cal(int x1, int y1, int x2, int y2){
		int dis;
		dis=Math.abs(x1-x2)+Math.abs(y1-y2);
		return dis;
	}
	static void backtrack(int idx , int currx, int curry, int currentdis  ){
		
		if(idx == n){
			int distohome = cal(currx,curry,hx,hy);
			int totaldis = distohome+currentdis;
			if(totaldis<ans){
				ans = totaldis;
			}
			return;
		}
		if(currentdis>ans){
			return;
		}
		for(int i = 1; i<=n;i++){
			if(!visited[i]){
				int dist=cal(currx,curry,map[i][0],map[i][1]);
				visited[i]=true;
				backtrack(idx+1,map[i][0],map[i][1],currentdis+dist);
				visited[i]=false;
			}
		}
		
		
		
	}
	
	
	
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		for(int tc = 1; tc<=T; tc++){
			ans = 1000000;
			sx=sc.nextInt();
			sy=sc.nextInt();
			hx=sc.nextInt();
			hy=sc.nextInt();
			n=sc.nextInt();
			map = new int[n+1][2];
			for(int i = 1;i<=n;i++){
				map[i][0]=sc.nextInt();
				map[i][1]=sc.nextInt();
			}
			visited=new boolean[n+1];
			for(int i = 1;i<=n;i++){
				visited[i] = false;
			}
			backtrack(0,sx,sy,0);
			System.out.println("Case #"+tc+" "+ans);
				
		}
	}

}



import java.util.Scanner;

public class Solution {

	static int xStart, yStart, xEnd, yEnd;
	static int N;
	static int[][] map = new int[20][3];
	static boolean[] visited = new boolean[20];
	static int ans;

	static int calLength(int x1, int y1, int x2, int y2) {
		return Math.abs(x1 - x2) + Math.abs(y1 - y2);
	}

	static void backtrack(int idx, int totalLength, int last) {
		if (totalLength > ans)
			return;

		if (idx == N) {
			int back = calLength(map[last][0], map[last][1], xEnd, yEnd);
			if (totalLength + back < ans)
				ans = totalLength + back;
			return;
		}

		for (int i = 1; i <= N; i++) {
			if (!visited[i]) {
				visited[i] = true;

				backtrack(idx + 1,totalLength+ calLength(map[last][0], map[last][1],map[i][0], map[i][1]), i);
				visited[i] = false;
			}
		}
	}

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int T = sc.nextInt();

		for (int tc = 1; tc <= T; tc++) {

			xStart = sc.nextInt();
			yStart = sc.nextInt();
			xEnd = sc.nextInt();
			yEnd = sc.nextInt();

			N = sc.nextInt();

			map[0][0] = xStart;
			map[0][1] = yStart;

			for (int i = 1; i <= N; i++) {
				map[i][0] = sc.nextInt();
				map[i][1] = sc.nextInt();
			}

			for (int i = 0; i < 20; i++)
				visited[i] = false;

			ans = 987654321;

			backtrack(0, 0, 0);

			System.out.println("Case #" + tc + " " + ans);
		}

		sc.close();
	}
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: