-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathday12.py
executable file
·64 lines (45 loc) · 1.09 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
#!/usr/bin/env python3
import sys
from collections import deque, defaultdict
def n_paths(G, src, dst):
stack = deque([(src, {src})])
total = 0
while stack:
node, visited = stack.pop()
if node == dst:
total += 1
continue
for n in G[node]:
if n in visited and n.islower():
continue
stack.append((n, visited | {n}))
return total
def n_paths2(G, src, dst):
stack = deque([(src, {src}, False)])
total = 0
while stack:
node, visited, double = stack.pop()
if node == dst:
total += 1
continue
for n in G[node]:
if n not in visited or n.isupper():
stack.append((n, visited | {n}, double))
continue
if double:
continue
stack.append((n, visited, True))
return total
# Open the first argument as input or use stdin if no arguments were given
fin = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin
G = defaultdict(list)
for edge in fin:
a, b = edge.rstrip().split('-')
if b != 'start':
G[a].append(b)
if a != 'start':
G[b].append(a)
n1 = n_paths(G, 'start', 'end')
n2 = n_paths2(G, 'start', 'end')
print('Part 1:', n1)
print('Part 2:', n2)