aoc/2021/12/12.py
2021-12-13 01:11:38 -06:00

42 lines
1.1 KiB
Python

adj = {}
with open("input.txt") as f:
for line in f.read().split('\n'):
[node1, node2] = line.split('-')
if node1 not in adj:
adj[node1] = set()
if node2 not in adj:
adj[node2] = set()
if node1 in adj and node2 in adj:
adj[node1].add(node2)
adj[node2].add(node1)
search = [['start']]
paths = []
while search:
path = search.pop()
current = path[-1]
for cave in adj[current]:
if cave == 'end':
paths.append(path+[cave])
elif cave.isupper() or cave not in path:
search.append(path+[cave])
print(len(paths))
search = [(['start'], True)]
paths = []
while search:
path, flag = search.pop()
current = path[-1]
for cave in adj[current]:
if cave == 'end':
paths.append(path+[cave])
elif cave == 'start':
continue # skip this case bc we can't go back
elif cave.isupper() or cave not in path: # big cave or unvisited,
search.append((path+[cave],flag)) # so explore further
elif flag: # we still haven't visited a cave twice,
search.append((path+[cave],False)) # so go there and explore, but remember we've used our exception
print(len(paths))