-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathday12.js
86 lines (74 loc) · 1.95 KB
/
day12.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
85
86
const fs = require("fs");
const graph = {};
const lines = fs
.readFileSync("day12.txt", { encoding: "utf-8" }) // read day??.txt content
.replace(/\r/g, "") // remove all \r characters to avoid issues on Windows
.split("\n") // Split on newline
.filter(Boolean) // Remove empty lines
.map((x) => {
const [from, to] = x.split("-");
if (!graph[from]) {
graph[from] = [];
}
if (!graph[to]) {
graph[to] = [];
}
graph[from].push(to);
graph[to].push(from);
return { from, to };
});
function isSmallCave(string) {
return /[a-z]/.test(string);
}
function part1() {
function depthFirstSearch(node, visited, paths) {
visited.push(node);
if (node === "end") {
paths.push(visited.join`,`);
return;
}
for (const neighbor of graph[node]) {
if (isSmallCave(neighbor) && visited.includes(neighbor)) {
continue;
}
depthFirstSearch(neighbor, [...visited], paths);
}
}
const paths = [];
depthFirstSearch("start", [], paths);
console.log(paths.length);
}
part1();
/**
* one small cave can be visited at most twice
* all other small caves can be visited at most once
*/
function part2() {
function depthFirstSearch(node, visited, visitedTwiceAlready, paths) {
visited.push(node);
if (node === "end") {
paths.push(visited.join`,`);
return;
}
for (const neighbor of graph[node]) {
if (neighbor === "start") {
continue;
}
if (isSmallCave(neighbor) && visited.includes(neighbor)) {
if (visitedTwiceAlready) {
continue;
}
if (visited.filter((x) => x === neighbor).length >= 2) {
continue;
}
depthFirstSearch(neighbor, [...visited], true, paths);
} else {
depthFirstSearch(neighbor, [...visited], visitedTwiceAlready, paths);
}
}
}
const paths = [];
depthFirstSearch("start", [], false, paths);
console.log(paths.length);
}
part2();