백준 15686 치킨 배달
import java.util.*;
import java.io.*;
class Point{
public int x;
public int y;
Point(int x, int y){
this.x = x;
this.y = y;
}
}
public class ChickenDelivery {
static int N;
static int M;
static int [][] map;
static int distance;
static boolean [] possible;
static ArrayList<Point> house;
static ArrayList<Point> chicken;
static void chickenDistance(int count, int index) {
if(count == M) {
int res = 0;
for(int i = 0; i < house.size(); i++) {
int min = Integer.MAX_VALUE;
for(int j = 0; j < chicken.size(); j++) {
if(possible[j])
min = Math.min(min, Math.abs(house.get(i).x - chicken.get(j).x) + Math.abs(house.get(i).y - chicken.get(j).y));
}
res += min;
}
distance = Math.min(distance, res);
}
for(int i = index; i < chicken.size(); i++) {
possible[i] = true;
chickenDistance(count+1, i+1);
possible[i] = false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
N = sc.nextInt();
M = sc.nextInt();
map = new int[N][N];
house = new ArrayList<>();
chicken = new ArrayList<>();
distance = Integer.MAX_VALUE;
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
map[i][j] = sc.nextInt();
if(map[i][j] == 1) {
house.add(new Point(i, j)) ;
}
if(map[i][j] == 2) {
chicken.add(new Point(i,j)) ;
}
}
}
possible = new boolean[chicken.size()];
chickenDistance(0, 0);
System.out.println(distance);
}
}