~noelle/aoc-2021

ab0e96c7c00e89196a6eec90b9bebae0c8a150b8 — Noelle Leigh 2 years ago f98d196
12_1
4 files changed, 84 insertions(+), 0 deletions(-)

A 12/README.md
A 12/example.txt
A 12/input.txt
A 12/puzzle_1.py
A 12/README.md => 12/README.md +3 -0
@@ 0,0 1,3 @@
Day 12: Passage Pathing

https://adventofcode.com/2021/day/12

A 12/example.txt => 12/example.txt +10 -0
@@ 0,0 1,10 @@
dc-end
HN-start
start-kj
dc-start
dc-HN
LN-dc
HN-end
kj-sa
kj-HN
kj-dc

A 12/input.txt => 12/input.txt +25 -0
@@ 0,0 1,25 @@
kc-qy
qy-FN
kc-ZP
end-FN
li-ZP
yc-start
end-qy
yc-ZP
wx-ZP
qy-li
yc-li
yc-wx
kc-FN
FN-li
li-wx
kc-wx
ZP-start
li-kc
qy-nv
ZP-qy
nv-xr
wx-start
end-nv
kc-nv
nv-XQ

A 12/puzzle_1.py => 12/puzzle_1.py +46 -0
@@ 0,0 1,46 @@
"""
Solution for AoC 2021 12 Puzzle 1

cat input.txt | python puzzle_1.py
"""
import sys

START = "start"
END = "end"


def route(path: list[str], segments: list[set[str, str]]) -> int:
    """
    Return the number of unique paths to "end" starting with a given path.
    `path` will always have at least two caves in it.
    """
    head = path[-1]
    if head == END:
        return 1

    connecting_segments = filter(lambda segment: head in segment, segments)
    path_total = 0
    for segment in connecting_segments:
        new_head = (segment - {head}).pop()
        # Skip small caves that were already visited
        if new_head.islower() and new_head in path:
            continue
        path_total += route([*path, new_head], segments)

    return path_total


if __name__ == "__main__":
    cave_segments = list(
        map(
            lambda line: set(line.split("-", maxsplit=1)), sys.stdin.read().splitlines()
        )
    )
    distinct_path_count = 0
    # Loop through all caves that connect to start
    starting_segments = filter(lambda segment: START in segment, cave_segments)
    for starting_segment in starting_segments:
        second_cave = (starting_segment - {START}).pop()
        distinct_path_count += route([START, second_cave], cave_segments)

    sys.stdout.write(str(distinct_path_count))