forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
7.java
107 lines (91 loc) · 3.28 KB
/
7.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.util.*;
class Combination {
private int n;
private int r;
private int[] now; // 현재 조합
private ArrayList<ArrayList<Position>> result; // 모든 조합
public ArrayList<ArrayList<Position>> getResult() {
return result;
}
public Combination(int n, int r) {
this.n = n;
this.r = r;
this.now = new int[r];
this.result = new ArrayList<ArrayList<Position>>();
}
public void combination(ArrayList<Position> arr, int depth, int index, int target) {
if (depth == r) {
ArrayList<Position> temp = new ArrayList<>();
for (int i = 0; i < now.length; i++) {
temp.add(arr.get(now[i]));
}
result.add(temp);
return;
}
if (target == n) return;
now[index] = target;
combination(arr, depth + 1, index + 1, target + 1);
combination(arr, depth, index, target + 1);
}
}
class Position {
private int x;
private int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
public class Main {
public static int n, m;
public static int[][] arr = new int[50][50];
public static ArrayList<Position> chicken = new ArrayList<>();
public static ArrayList<Position> house = new ArrayList<>();
public static int getSum(ArrayList<Position> candidates) {
int result = 0;
// 모든 집에 대하여
for (int i = 0; i < house.size(); i++) {
int hx = house.get(i).getX();
int hy = house.get(i).getY();
// 가장 가까운 치킨 집을 찾기
int temp = (int) 1e9;
for (int j = 0; j < candidates.size(); j++) {
int cx = candidates.get(j).getX();
int cy = candidates.get(j).getY();
temp = Math.min(temp, Math.abs(hx - cx) + Math.abs(hy - cy));
}
// 가장 가까운 치킨 집까지의 거리를 더하기
result += temp;
}
// 치킨 거리의 합 반환
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
for (int r = 0; r < n; r++) {
for (int c = 0; c < n; c++) {
arr[r][c] = sc.nextInt();
if (arr[r][c] == 1) house.add(new Position(r, c)); // 일반 집
else if (arr[r][c] == 2) chicken.add(new Position(r, c)); // 치킨집
}
}
// 모든 치킨 집 중에서 m개의 치킨 집을 뽑는 조합 계산
Combination comb = new Combination(chicken.size(), m);
comb.combination(chicken, 0, 0, 0);
ArrayList<ArrayList<Position>> chickenList = comb.getResult();
// 치킨 거리의 합의 최소를 찾아 출력
int result = (int) 1e9;
for (int i = 0; i < chickenList.size(); i++) {
result = Math.min(result, getSum(chickenList.get(i)));
}
System.out.println(result);
}
}