-
Notifications
You must be signed in to change notification settings - Fork 0
/
part1.ts
51 lines (44 loc) · 1.19 KB
/
part1.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
import * as fs from 'fs';
const input = fs.readFileSync('input', 'utf8').split('\n').map((line => line.split('')));
const directions = [
{ x: -1, y: 0 },
{ x: 0, y: 1 },
{ x: 1, y: 0 },
{ x: 0, y: -1 },
];
const getArea = (x: number, y: number, area: Set<string>) => {
const key = `${x},${y}`;
if (!area.has(key)) {
area.add(key);
for (const direction of directions) {
if (input[y][x] === input[y + direction.y]?.[x + direction.x]) {
getArea(x + direction.x, y + direction.y, area);
}
}
}
};
const getFenceCount = (key: string) => {
const [x, y] = key.split(',').map(Number);
let count = 4;
for (const direction of directions) {
if (input[y][x] === input[y + direction.y]?.[x + direction.x]) {
count--;
}
}
return count;
}
let result = 0;
let visited = new Set<string>();
for (let y = 0; y < input.length; y++) {
for (let x = 0; x < input[y].length; x++) {
const key = `${x},${y}`;
if (!visited.has(key)) {
const area = new Set<string>();
getArea(x, y, area);
visited = new Set([...visited, ...area]);
const fenceCount = Array.from(area).reduce((acc, plot) => acc + getFenceCount(plot), 0);
result += area.size * fenceCount;
}
}
}
console.log(result);