-
Notifications
You must be signed in to change notification settings - Fork 0
/
d12.ts
97 lines (87 loc) · 2.26 KB
/
d12.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
function parse(input: string) {
return input.split("\n").map((line) => line.split(""));
}
function fence(garden: string[][]) {
const visited: Set<string> = new Set();
function countCorners([i, j]: number[], label: string) {
let corners = 0;
const same = (x: number, y: number) => garden[x]?.[y] === label;
// prettier-ignore
const exterior = [
[[-1, 0], [0, -1]],
[[-1, 0], [0, 1]],
[[1, 0], [0, -1]],
[[1, 0], [0, 1]],
];
// prettier-ignore
const interior = [
[[0, -1], [-1, 0], [-1, -1]],
[[0, 1], [-1, 0], [-1, 1]],
[[0, -1], [1, 0], [1, -1]],
[[0, 1], [1, 0], [1, 1]],
];
exterior.forEach((neighbors) => {
const [[ax, ay], [bx, by]] = neighbors;
if (!same(i + ax, j + ay) && !same(i + bx, j + by)) {
corners++;
}
});
interior.forEach((neighbors) => {
const [[ax, ay], [bx, by], [cx, cy]] = neighbors;
if (
same(i + ax, j + ay) &&
same(i + bx, j + by) &&
!same(i + cx, j + cy)
) {
corners++;
}
});
return corners;
}
function flood(
[i, j]: number[],
label: string,
perimeter = 0,
corners = 0,
area = 1
) {
visited.add(`${i},${j}`);
// prettier-ignore
const neighbors = [[i - 1, j], [i, j - 1], [i + 1, j], [i, j + 1]];
corners += countCorners([i, j], label);
neighbors.forEach(([x, y]) => {
if (garden[x]?.[y] !== label) {
perimeter++;
} else {
if (!visited.has(`${x},${y}`)) {
const f = flood([x, y], label, perimeter, corners, area);
perimeter = f.perimeter;
area = f.area + 1;
corners = f.corners;
}
}
});
return { perimeter, corners, area };
}
const regions = [];
for (let i = 0; i < garden.length; i++) {
for (let j = 0; j < garden[i].length; j++) {
if (!visited.has(`${i},${j}`)) {
regions.push(flood([i, j], garden[i][j]));
}
}
}
return regions;
}
export function p1(input: string) {
return fence(parse(input)).reduce(
(acc, { perimeter, area }) => acc + perimeter * area,
0
);
}
export function p2(input: string) {
return fence(parse(input)).reduce(
(acc, { corners, area }) => acc + corners * area,
0
);
}