Skip to content

Instantly share code, notes, and snippets.

@Mu-adventofcode
Last active May 4, 2022 07:01
Show Gist options
  • Save Mu-adventofcode/049c172b0720d34d030e4b4ed48dc724 to your computer and use it in GitHub Desktop.
Save Mu-adventofcode/049c172b0720d34d030e4b4ed48dc724 to your computer and use it in GitHub Desktop.
Advent of Code 2021 day 12 part 1 iterator version
"""
My solution for Advent of Code 2021 day 12 part 1.
This version uses an iterator to implement depth-first-search.
The algorithm is based on networkx.all_simple_paths().
"""
from collections import defaultdict
DEAD_END = object()
def route(adjacents):
curpath = ["start"]
stack = [iter(adjacents["start"])]
while stack:
adjs = stack[-1]
cave = next(adjs, DEAD_END)
if cave is DEAD_END:
curpath.pop()
stack.pop()
elif cave in curpath and cave.islower():
continue
elif cave == "end":
yield 1
else:
curpath.append(cave)
stack.append(iter(adjacents[cave]))
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(sum(route(adjacents)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment