My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add 2021/12

+45
+45
2021/day12.py
··· 1 + import copy 2 + import fileinput 3 + from collections import Counter, defaultdict 4 + 5 + 6 + graph = defaultdict(set) 7 + smalls = set() 8 + 9 + for line in fileinput.input(): 10 + a, b = line.strip().split('-') 11 + 12 + graph[a].add(b) 13 + graph[b].add(a) 14 + 15 + 16 + def dfs(start, extra_time=False): 17 + num_paths = [0] 18 + def _dfs(node, seen=None, doubled=False): 19 + if seen is None: 20 + seen = Counter({'start': 1 if extra_time else 0}) 21 + 22 + if node == 'end': 23 + num_paths[0] += 1 24 + return 25 + 26 + # If small cave, check if part 1/2 and skip accordingly. 27 + if node == node.lower(): 28 + if (doubled or not extra_time) and seen[node] >= 1: 29 + return 30 + elif not doubled and seen[node] >= 2: 31 + return 32 + 33 + seen[node] += 1 34 + if node == node.lower() and node not in ('start', 'end') and seen[node] >= 2: 35 + doubled = True 36 + 37 + for n in graph[node]: 38 + _dfs(n, copy.deepcopy(seen), doubled=doubled) 39 + 40 + _dfs(start) 41 + return num_paths[0] 42 + 43 + 44 + print "Part 1:", dfs('start') 45 + print "Part 2:", dfs('start', extra_time=True)