forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path7.java
More file actions
107 lines (91 loc) Β· 3.28 KB
/
7.java
File metadata and controls
107 lines (91 loc) Β· 3.28 KB
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);
}
}