Last active
May 4, 2022 07:01
-
-
Save Mu-adventofcode/049c172b0720d34d030e4b4ed48dc724 to your computer and use it in GitHub Desktop.
Advent of Code 2021 day 12 part 1 iterator 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
""" | |
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