-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathA13.js
More file actions
55 lines (44 loc) · 1.38 KB
/
A13.js
File metadata and controls
55 lines (44 loc) · 1.38 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
const fs = require('fs');
const path = require('path')
const input = fs.readFileSync(path.join(__dirname,'/A13.txt')).toString().trim().split("\n");
const [n, m] = input.shift().split(" ").map((v) => +v);
let [chicken, house] = [[], []];
//console.log(input);
for (let i = 0; i < n; i++) {
let tmp = input.shift().split(" ").map((v) => +(v.trim()));
for (let j = 0; j < n; j++) {
if (tmp[j] === 1) {
house.push([i, j]);
} else if (tmp[j] === 2) {
chicken.push([i, j]);
}
}
}
let result = Infinity;
let total_chicken = getCombinations(chicken, m);
for (let i of total_chicken) {
result = Math.min(result, get_min(i));
}
console.log(result);
function get_min(chicken) {
let result = 0;
for (let [x, y] of house) {
let min = Infinity;
for (let [i, j] of chicken) {
min = Math.min(min, Math.abs(x - i) + Math.abs(y - j));
}
result += min;
}
return result;
}
function getCombinations(arr, selectNum) {
const results = [];
if (selectNum === 1) return arr.map((value) => [value]);
arr.forEach((fixed, index) => {
const rest = arr.slice(index + 1);
const combinations = getCombinations(rest, selectNum - 1);
const attached = combinations.map((combination) => [fixed, ...combination]);
results.push(...attached);
});
return results;
};