-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12.py
54 lines (37 loc) · 1.02 KB
/
12.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
from lib import *
input = read_input(2021, 12)
lines = input.splitlines()
edges = {}
for line in lines:
a, b = line.split("-")
edges.setdefault(a, []).append(b)
edges.setdefault(b, []).append(a)
def search1(node, visited):
if node == "end":
return 1
if node.islower() and node in visited:
return 0
visited.add(node)
out = sum(search1(n, visited) for n in edges.get(node, []))
visited.discard(node)
return out
print(search1("start", set()))
edges = {}
for line in lines:
a, b = line.split("-")
edges.setdefault(a, []).append(b)
edges.setdefault(b, []).append(a)
def search2(node, visited, twice):
if node == "end":
return 1
tw = False
if node.islower() and node in visited:
if twice or node == "start":
return 0
tw = True
visited.add(node)
out = sum(search2(n, visited, twice or tw) for n in edges.get(node, []))
if not tw:
visited.discard(node)
return out
print(search2("start", set(), False))