-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBAEKJOON_15686
More file actions
75 lines (68 loc) · 2.2 KB
/
BAEKJOON_15686
File metadata and controls
75 lines (68 loc) · 2.2 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
import java.io.*;
import java.util.*;
public class Main{
int x;
int y;
public Main(int x, int y) {
this.x = x;
this.y = y;
}
static int N;
static int M;
public static List<Main> house;
public static List<Main> chicken;
static int min=Integer.MAX_VALUE;
public static boolean[] v;
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 st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
int[][] arr = new int[N][N];
house = new ArrayList<>();
chicken = new ArrayList<>();
for(int i=0; i<N; i++){
st= new StringTokenizer(br.readLine());
for(int j=0; j<N; j++){
int number = Integer.parseInt(st.nextToken());
arr[i][j] = number;
if(number==1){
house.add(new Main(i,j));
}
if(number==2){
chicken.add(new Main(i,j));
}
}
}
v = new boolean[chicken.size()];
backtracking(0,0);
bw.write(String.valueOf(min));
bw.flush();
bw.close();
}
public static void backtracking(int count, int index){
if(count==M){
int total=0;
for(int i=0; i<house.size(); i++){
int sum =Integer.MAX_VALUE;
for(int j=0; j<chicken.size(); j++){
if(v[j]==true){
int distance = Math.abs(house.get(i).x - chicken.get(j).x) + Math.abs(house.get(i).y-chicken.get(j).y);
sum = Math.min(distance,sum);
}
}
total = total+sum;
}
min = Math.min(total, min);
return;
}
for(int i=index; i<v.length; i++){
if(v[i]==false){
v[i]=true;
backtracking(count+1, i+1);
v[i]=false;
}
}
}
}