-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnine.js
More file actions
99 lines (81 loc) · 1.78 KB
/
Copy pathnine.js
File metadata and controls
99 lines (81 loc) · 1.78 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
import { readFile } from 'fs/promises';
async function init() {
const input = await readFile('nine.txt', 'utf8');
const MATRIX = input.split('\n').map((line) => {
return line.split('').map((d) => parseInt(d));
});
const lowPoints = [];
MATRIX.forEach((row, i) => {
row.forEach((d, j) => {
if (isLow(MATRIX, i, j)) {
lowPoints.push({
i,
j,
d,
});
}
});
});
const basins = lowPoints.map(({ i, j, d }) => {
const basin = new Set();
addToBasin(MATRIX, basin, i, j);
return { i, j, size: basin.size };
});
basins.sort((a, b) => b.size - a.size);
console.log(basins[0].size * basins[1].size * basins[2].size);
}
function addToBasin(grid, basin, i, j) {
if (!inside(grid, i, j)) {
return;
}
if (grid[i][j] === 9) {
return;
}
const point = `${i}-${j}`;
if (basin.has(point)) {
return;
}
basin.add(point);
// add neighbors;
addToBasin(grid, basin, i - 1, j);
addToBasin(grid, basin, i + 1, j);
addToBasin(grid, basin, i, j - 1);
addToBasin(grid, basin, i, j + 1);
}
function inside(grid, x, y) {
if (x < 0) {
return false;
}
if (x === grid.length) {
return false;
}
if (y < 0) {
return false;
}
if (y === grid[0].length) {
return false;
}
return true;
}
function isLow(grid, i, j) {
const neighbors = [];
if (inside(grid, i - 1, j)) {
neighbors.push(grid[i - 1][j]);
}
if (inside(grid, i, j - 1)) {
neighbors.push(grid[i][j - 1]);
}
if (inside(grid, i, j + 1)) {
neighbors.push(grid[i][j + 1]);
}
if (inside(grid, i + 1, j)) {
neighbors.push(grid[i + 1][j]);
}
for (let ind = 0; ind < neighbors.length; ind++) {
if (grid[i][j] >= neighbors[ind]) {
return false;
}
}
return true;
}
init();