-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.ts
79 lines (73 loc) · 1.76 KB
/
part2.ts
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
import * as fs from 'fs';
const input = fs
.readFileSync('input', 'utf8')
.split('\n')
.map((x) => x.split(''));
const rows = input.length;
const columns = input[0].length;
const shifts = [
[-1, 0],
[0, 1],
[1, 0],
[0, -1],
]; // up, right, down, left
const entryPoints = [
...input[0]
.map((_, i, r) => [
{ row: 0, column: i, direction: 2 },
{ row: r.length - 1, column: i, direction: 0 },
])
.flat(),
...input
.map((x, i) => [
{ row: i, column: 0, direction: 1 },
{ row: i, column: x.length - 1, direction: 3 },
])
.flat(),
];
let result = 0;
for (const entryPoint of entryPoints) {
const checked = {};
const energized = Array(rows)
.fill(0)
.map(() => Array(columns).fill('.'));
const queue = [entryPoint];
while (queue.length > 0) {
const { row, column, direction } = queue.pop();
const key = [row, column, direction].join(',');
if (checked[key]) continue;
checked[key] = true;
if (row >= 0 && row < rows && column >= 0 && column < columns) {
energized[row][column] = '#';
const directions = [];
switch (input[row][column]) {
case '|':
if (direction % 2) directions.push(0, 2);
else directions.push(direction);
break;
case '-':
if (!(direction % 2)) directions.push(1, 3);
else directions.push(direction);
break;
case '/':
directions.push(direction ^ 1);
break;
case '\\':
directions.push(direction ^ 3);
break;
default:
directions.push(direction);
break;
}
for (const direction of directions) {
queue.push({
row: row + shifts[direction][0],
column: column + shifts[direction][1],
direction: direction,
});
}
}
}
result = Math.max(result, energized.flat().filter((x) => x === '#').length);
}
console.log(result);