Last active
May 4, 2022 07:02
-
-
Save Mu-adventofcode/1dc02ce7bc0135021aa57d170c2e3991 to your computer and use it in GitHub Desktop.
Advent of Code day 12 part 1 recursive version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Advent of Code 2021 day 12 part 1. | |
This version makes use of recursive function calls to implement | |
depth-first-search. | |
""" | |
from collections import defaultdict | |
def count_paths(caves_seen): | |
path_count = 0 | |
cave = caves_seen[-1] | |
for adj in adjacents[cave]: | |
if adj in caves_seen and adj.islower(): | |
continue | |
if adj == "end": | |
path_count += 1 | |
else: | |
path_count += count_paths(caves_seen + [adj]) | |
return path_count | |
adjacents = defaultdict(set) | |
with open("input_12.txt") as f: | |
for line in f: | |
c1, c2 = tuple(line.strip().split("-")) | |
adjacents[c1].add(c2) | |
adjacents[c2].add(c1) | |
print(count_paths(["start"])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment