|
| 1 | +import path from "node:path"; |
| 2 | +import {readInputLineByLine} from "@utils/io"; |
| 3 | + |
| 4 | +export async function part1(inputFile: string) { |
| 5 | + return await day11(inputFile, countPaths); |
| 6 | +} |
| 7 | + |
| 8 | +export async function part2(inputFile: string) { |
| 9 | + return await day11(inputFile); |
| 10 | +} |
| 11 | + |
| 12 | +async function day11(inputFile: string, calcFn?: (graph: Map<string, string[]>) => number) { |
| 13 | + const inputPath = path.join(__dirname, inputFile); |
| 14 | + const lines = await readInputLineByLine(inputPath); |
| 15 | + const graph = parseGraph(lines); |
| 16 | + return calcFn?.(graph); |
| 17 | +} |
| 18 | + |
| 19 | +function countPaths(graph: Map<string, string[]>): number { |
| 20 | + const memo = new Map<string, number>(); |
| 21 | + const visiting = new Set<string>(); |
| 22 | + |
| 23 | + const dfs = (node: string): number => { |
| 24 | + if (node === "out") return 1; |
| 25 | + const cached = memo.get(node); |
| 26 | + if (cached !== undefined) return cached; |
| 27 | + if (visiting.has(node)) { |
| 28 | + return 0; |
| 29 | + } |
| 30 | + visiting.add(node); |
| 31 | + const neighbors = graph.get(node) ?? []; |
| 32 | + let total = 0; |
| 33 | + for (const next of neighbors) { |
| 34 | + total += dfs(next); |
| 35 | + } |
| 36 | + visiting.delete(node); |
| 37 | + memo.set(node, total); |
| 38 | + return total; |
| 39 | + }; |
| 40 | + |
| 41 | + return dfs("you"); |
| 42 | +} |
| 43 | + |
| 44 | +function parseGraph(lines: string[]): Map<string, string[]> { |
| 45 | + const graph = new Map<string, string[]>(); |
| 46 | + for (const raw of lines) { |
| 47 | + const line = raw.trim(); |
| 48 | + if (line.length === 0) |
| 49 | + continue; |
| 50 | + const [fromPart, toPart] = line.split(":"); |
| 51 | + const from = fromPart.trim(); |
| 52 | + if (!from) |
| 53 | + continue; |
| 54 | + const outputs = toPart?.trim() |
| 55 | + ? toPart.trim().split(/\s+/) |
| 56 | + : []; |
| 57 | + graph.set(from, outputs); |
| 58 | + } |
| 59 | + return graph; |
| 60 | +} |
0 commit comments