-
Notifications
You must be signed in to change notification settings - Fork 0
/
day12.py
92 lines (81 loc) · 1.61 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
from collections import defaultdict
SAMPLE_INPUT_1 = [
"start-A",
"start-b",
"A-c",
"A-b",
"b-d",
"A-end",
"b-end",
]
SAMPLE_INPUT_2 = [
"dc-end",
"HN-start",
"start-kj",
"dc-start",
"dc-HN",
"LN-dc",
"HN-end",
"kj-sa",
"kj-HN",
"kj-dc",
]
SAMPLE_INPUT_3 = [
"fs-end",
"he-DX",
"fs-he",
"start-DX",
"pj-DX",
"end-zg",
"zg-sl",
"zg-pj",
"pj-he",
"RW-he",
"fs-DX",
"pj-RW",
"zg-RW",
"start-pj",
"he-WI",
"zg-he",
"pj-fs",
"start-RW",
]
def solve(lines, bonus):
edges = defaultdict(set)
for line in lines:
lhs, rhs = line.strip().split("-", maxsplit=2)
edges[lhs].add(rhs)
edges[rhs].add(lhs)
def walk(current, path, bonus):
if current == "end":
yield path
else:
for next in edges[current]:
if next == "start":
pass
elif next.isupper() or next not in path:
yield from walk(next, path + [next], bonus)
elif bonus and next.islower():
yield from walk(next, path + [next], False)
return sum(1 for _ in walk("start", ["start"], bonus))
def part1(lines):
"""
>>> part1(SAMPLE_INPUT_1)
10
>>> part1(SAMPLE_INPUT_2)
19
>>> part1(SAMPLE_INPUT_3)
226
"""
return solve(lines, False)
def part2(lines):
"""
>>> part2(SAMPLE_INPUT_1)
36
>>> part2(SAMPLE_INPUT_2)
103
>>> part2(SAMPLE_INPUT_3)
3509
"""
return solve(lines, True)
parts = (part1, part2)