포인트는 조합 구하기!!
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
static int answer = Integer.MAX_VALUE;
public static void main(String... args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer tokenizer = new StringTokenizer(br.readLine());
int N = Integer.parseInt(tokenizer.nextToken());
int M = Integer.parseInt(tokenizer.nextToken());
int[][] arr = new int[N][N];
List<int[]> chickenStore = new ArrayList<>();
List<int[]> houses = new ArrayList<>();
for (int i = 0; i < N; i++) {
tokenizer = new StringTokenizer(br.readLine());
for (int j = 0; j < N; j++) {
int type = Integer.parseInt(tokenizer.nextToken());
arr[i][j] = type;
if (type == 2) {
chickenStore.add(new int[]{i, j});
} else if (type == 1) {
houses.add(new int[]{i, j});
}
}
}
br.close();
boolean[] visited = new boolean[chickenStore.size()];
combination(chickenStore, houses, visited, 0, chickenStore.size(), M);
bw.write(String.valueOf(answer));
bw.flush();
bw.close();
}
static void combination(List<int[]> ckList, List<int[]> houses, boolean[] visited, int depth, int n, int r) {
if (r == 0) {
// houses 순회하면서 각 집들과 visited == true 인 치킨집과 비교해서 치킨거리 구하고
// 모든 치킨집 경우의 수의 치킨거리의 합 중 가장 작은게 답...
int sum = 0;
for (int i = 0; i < houses.size(); i++) {
int min = Integer.MAX_VALUE;
for (int j=0; j<visited.length; j++) {
if (visited[j]) {
int[] coord = ckList.get(j);
min = Math.min(min, calculateDistance(houses.get(i)[0], houses.get(i)[1], coord[0], coord[1]));
}
}
sum += min;
}
answer = Math.min(answer, sum);
return ;
}
if (depth == n) {
return ;
}
visited[depth] = true;
combination(ckList, houses, visited, depth + 1, n, r - 1); // 나를 포함하는 경우
visited[depth] = false;
combination(ckList, houses, visited, depth + 1, n, r); // 나를 포함하지 않는 경우
}
static int calculateDistance(int x1, int y1, int x2, int y2) {
return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}
}