-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpuzzle2.ts
77 lines (61 loc) · 1.71 KB
/
puzzle2.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
import { readInput } from '../utils';
class CaveMap {
private caveRoutes: Map<string, string[]>;
constructor() {
this.caveRoutes = new Map();
}
addLink(cave1: string, cave2: string) {
const routesCave1 = this.caveRoutes.get(cave1) ?? [];
this.caveRoutes.set(cave1, [...routesCave1, cave2]);
const routesCave2 = this.caveRoutes.get(cave2) ?? [];
this.caveRoutes.set(cave2, [...routesCave2, cave1]);
}
findPaths() {
return this.findPathsRecursive('start', [], false);
}
private findPathsRecursive(
from: string,
usedSmallCaves: string[],
haveUsedASmallCaveTwice: boolean
): number {
let visitedSmallCaves = [...usedSmallCaves];
let didUseSmallCaveASecondTime = false;
if (/^[a-z]+$/.test(from)) {
if (usedSmallCaves.includes(from)) {
if (haveUsedASmallCaveTwice || from === 'start') {
return 0;
} else {
didUseSmallCaveASecondTime = true;
}
}
visitedSmallCaves.push(from);
}
if (from === 'end') {
return 1;
}
const caves = this.caveRoutes.get(from);
if (!caves) {
throw new Error('Initial cave name not linked to other caves');
}
return caves.reduce((acc, curr) => {
return (
acc +
this.findPathsRecursive(
curr,
visitedSmallCaves,
haveUsedASmallCaveTwice || didUseSmallCaveASecondTime
)
);
}, 0);
}
}
function solve(fileName: string) {
const input = readInput(fileName);
const caveMap = new CaveMap();
input.forEach((line) => {
const [cave1, cave2] = line.split('-');
caveMap.addLink(cave1, cave2);
});
return caveMap.findPaths();
}
console.log('Solution:', solve('./input'));