-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday12.py
executable file
·44 lines (32 loc) · 1.07 KB
/
day12.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/env python3
# Day 12: Passage Pathing
# https://adventofcode.com/2021/day/12
import sys
from collections import defaultdict
data = open("input.txt" if len(sys.argv) == 1 else sys.argv[1]).read().splitlines()
nodes = defaultdict(list)
for line in data:
a, b = line.split("-")
nodes[a].append(b)
nodes[b].append(a)
def paths(visit_small_twice):
count = 0
heap = [("start", set(["start"]), None)]
while heap:
node, once, twice = heap.pop()
if node == "end":
count += 1
continue
for dest in nodes[node]:
if dest not in once:
if dest.lower() == dest:
new_once = once.copy()
new_once.add(dest)
heap.append((dest, new_once, twice))
else:
heap.append((dest, once, twice))
elif visit_small_twice and twice is None and dest in once and dest != "end" and dest != "start":
heap.append((dest, once, dest))
return count
print(paths(False))
print(paths(True))