|
| 1 | +import numpy as np |
| 2 | +from collections import defaultdict |
| 3 | +eg = "start-A\nstart-b\nA-c\nA-b\nb-d\nA-end\nb-end\n""" |
| 4 | + |
| 5 | + |
| 6 | +def p1visit(adj, lc, node, visited, twice, routes): |
| 7 | + visited.append(node) |
| 8 | + #print(visited) |
| 9 | + if node == 'end': |
| 10 | + routes.append('-'.join(visited)) |
| 11 | + else: |
| 12 | + [p1visit(adj, lc, d, visited.copy(), False, routes) for d in sorted(adj[node]) if not ((d in lc) and (d in visited))] |
| 13 | + |
| 14 | +def p2visit(adj, lc, node, visited, twice, routes): |
| 15 | + visited.append(node) |
| 16 | + if node == 'end': |
| 17 | + routes.append('-'.join(visited)) |
| 18 | + else: |
| 19 | + if not twice: |
| 20 | + [p2visit(adj, lc, d, visited.copy(), True, routes) for d in sorted(adj[node]) if (d in lc) and (d in visited) and (d not in ('start', 'end'))] |
| 21 | + [p2visit(adj, lc, d, visited.copy(), twice, routes) for d in sorted(adj[node]) if not ((d in lc) and (d in visited))] |
| 22 | + |
| 23 | + |
| 24 | +def router(eg, visitor): |
| 25 | + adj = defaultdict(list) |
| 26 | + lc = set() |
| 27 | + for line in filter(None,eg.split('\n')): |
| 28 | + a,b = line.strip().split("-") |
| 29 | + adj[a].append(b) |
| 30 | + adj[b].append(a) |
| 31 | + if a.lower() == a: |
| 32 | + lc.add(a) |
| 33 | + if b.lower() == b: |
| 34 | + lc.add(b) |
| 35 | + #lc.remove('start') |
| 36 | + #lc.remove('end') |
| 37 | + print(adj) |
| 38 | + print(lc) |
| 39 | + |
| 40 | + routes = [] |
| 41 | + visitor(adj, lc, 'start', [], False, routes) |
| 42 | + print(routes) |
| 43 | + print(len(routes)) |
| 44 | + |
| 45 | +router(eg, p1visit) |
| 46 | +#router("dc-end\nHN-start\nstart-kj\ndc-start\ndc-HN\nLN-dc\nHN-end\nkj-sa\nkj-HN\nkj-dc\n", p1visit) |
| 47 | +#router("fs-end\nhe-DX\nfs-he\nstart-DX\npj-DX\nend-zg\nzg-sl\nzg-pj\npj-he\nRW-he\nfs-DX\npj-RW\nzg-RW\nstart-pj\nhe-WI\nzg-he\npj-fs\nstart-RW\n", p1visit) |
| 48 | +#with open('input/day12.txt') as f: |
| 49 | +# router(f.read(), p1visit) |
| 50 | + |
| 51 | +router(eg, p2visit) |
| 52 | +router("dc-end\nHN-start\nstart-kj\ndc-start\ndc-HN\nLN-dc\nHN-end\nkj-sa\nkj-HN\nkj-dc\n", p2visit) |
| 53 | +router("fs-end\nhe-DX\nfs-he\nstart-DX\npj-DX\nend-zg\nzg-sl\nzg-pj\npj-he\nRW-he\nfs-DX\npj-RW\nzg-RW\nstart-pj\nhe-WI\nzg-he\npj-fs\nstart-RW\n", p2visit) |
| 54 | +with open('input/day12.txt') as f: |
| 55 | + router(f.read(), p2visit) |
| 56 | + |
0 commit comments