-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathB15686.java
More file actions
74 lines (55 loc) · 1.65 KB
/
B15686.java
File metadata and controls
74 lines (55 loc) · 1.65 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
package Practice;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class B15686 { //ġŲ ¹è´Þ
static int N, M, ans;
static int[][] map;
static ArrayList<int[]> home, chickenAll;
static int[][] chicken;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
home = new ArrayList<>();
chickenAll = new ArrayList<>();
chicken = new int[M][2];
map = new int[N][N];
for(int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for(int j = 0; j < N; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
if(map[i][j] == 1) home.add(new int[] {i, j});
else if(map[i][j] == 2) chickenAll.add(new int[] {i, j});
}
}
ans = Integer.MAX_VALUE;
solve(0, 0);
System.out.println(ans);
}
static void solve(int index, int count) {
if(count == M) {
int res = 0;
for(int i = 0; i < home.size(); i++) {
int min = Integer.MAX_VALUE;
int[] h = home.get(i);
for(int j = 0; j < M; j++) {
int[] c = chicken[j];
min = Math.min(min, Math.abs(h[0] - c[0]) + Math.abs(h[1] - c[1]));
}
res += min;
}
ans = Math.min(ans, res);
return;
}
for(int i = index; i < chickenAll.size(); i++) {
int[] c = chickenAll.get(i);
chicken[count][0] = c[0];
chicken[count][1] = c[1];
solve(i + 1, count + 1);
}
}
}