Skip to content

Instantly share code, notes, and snippets.

@Mu-adventofcode
Last active May 4, 2022 07:02
Show Gist options
  • Save Mu-adventofcode/1dc02ce7bc0135021aa57d170c2e3991 to your computer and use it in GitHub Desktop.
Save Mu-adventofcode/1dc02ce7bc0135021aa57d170c2e3991 to your computer and use it in GitHub Desktop.
Advent of Code day 12 part 1 recursive version
"""
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