-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.js
68 lines (68 loc) · 2.21 KB
/
solution.js
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
const filePath = require('path').join(__dirname, 'input');
const [num, ...arr] = require('fs')
.readFileSync(filePath)
.toString()
.trim()
.split('\n');
const [r, c, t] = num.split(' ');
function solution (r, c, t, arr) {
const top = {
index: 0,
distance: [[0, 1], [-1, 0], [0, -1], [1, 0]]
}
const bottom = {
index: 0,
distance: [[-1, 0], [0, 1], [1, 0], [0, -1]]
}
const airCleaner = [];
for (let i = 2; i < r - 2; i++) {
if (arr[i][0] === -1) {
airCleaner.push(i);
airCleaner.push(i + 1);
break;
}
}
const cleanToAir = ([y, x], [startRow, endRow], { index, distance }) => {
let dust = 0;
while (true) {
const [dy, dx] = distance[index];
const [ny, nx] = [dy + y, dx + x];
if (ny < startRow || ny >= endRow || nx < 0 || nx >= c) {
index = (index + 1) % 4;
continue;
}
if (arr[ny][nx] === -1) break;
[dust, arr[ny][nx]] = [arr[ny][nx], dust];
[y, x] = [ny, nx];
}
}
const spreadOfDust = () => {
let queue = [];
for (let i = 0; i < r; i++) {
for (let j = 0; j < c; j++) {
if (arr[i][j] > 0) {
queue.push([i, j, parseInt(arr[i][j] / 5)]);
}
}
}
let i = 0;
const distance = [[0, 1], [-1, 0], [1, 0], [0, -1]];
while (i < queue.length) {
const [y, x, dust] = queue[i++];
for (let [dy, dx] of distance) {
const [ny, nx] = [dy + y, dx + x];
if (ny < 0 || ny >= r || nx < 0 || nx >= c) continue;
if (arr[ny][nx] === -1) continue;
arr[ny][nx] += dust;
arr[y][x] -= dust
}
}
}
for (let i = 0; i < t; i ++) {
spreadOfDust();
cleanToAir([airCleaner[0], 0], [0, airCleaner[0] + 1], top);
cleanToAir([airCleaner[1], 0], [airCleaner[1], r], bottom);
}
return arr.reduce((acc, cur) => acc + cur.reduce((acc, cur) => acc + cur , 0), 2);
}
console.log(solution(+r, +c, +t, arr.map(r => r.split(' ').map(Number))));