-
Notifications
You must be signed in to change notification settings - Fork 0
/
part2.js
84 lines (73 loc) · 1.67 KB
/
part2.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const { readFileSync } = require("fs");
// Parse Input
const inputFile = "input.txt";
const input = readFileSync(inputFile).toString();
const grid = [];
input
.trim()
.split("\n")
.forEach((line) => grid.push(line.split("")));
let trailheads = [];
for (let y = 0; y < grid.length; y++) {
const line = grid[y];
for (let x = 0; x < line.length; x++) {
const element = line[x];
if (element == "0") {
trailheads.push({
id: trailheads.length,
start: [x, y],
});
}
}
}
const directions = [
[0, -1],
[-1, 0],
[1, 0],
[0, 1],
];
function isInGrid(coord) {
let x = coord[0];
let y = coord[1];
return !(x < 0 || y < 0 || x >= grid[0].length || y >= grid.length);
}
function computeTrailhead(th) {
const path = [
{
thId: th.id,
currentValue: 0,
coord: th.start,
},
];
let endCoords = [];
while (path.length > 0) {
let currentPath = path.pop();
let currentValue = currentPath.currentValue;
let coord = currentPath.coord;
directions.forEach((d) => {
let checkedCoord = [coord[0] + d[0], coord[1] + d[1]];
if (
isInGrid(checkedCoord) &&
currentValue == 8 &&
grid[checkedCoord[1]][checkedCoord[0]] == 9
) {
endCoords.push(checkedCoord);
} else if (
isInGrid(checkedCoord) &&
grid[checkedCoord[1]][checkedCoord[0]] == currentValue + 1
) {
path.push({
thId: th.id,
currentValue: currentValue + 1,
coord: checkedCoord,
});
}
});
}
return endCoords.length;
}
let result = 0;
trailheads.forEach((th) => {
result += computeTrailhead(th);
});
console.log(result);