-
Notifications
You must be signed in to change notification settings - Fork 0
/
a12.py
89 lines (70 loc) · 2.09 KB
/
a12.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
example = """
start-A
start-b
A-c
A-b
b-d
A-end
b-end
""".strip()
f = open("input/12.input")
text = f.read().strip()
def parse(t):
graph = {}
for line in t.split("\n"):
left, right = line.split('-')
if left not in graph:
graph[left] = set()
if right not in graph:
graph[right] = set()
graph[left].add(right)
graph[right].add(left)
return graph
def paths(graph):
queue = [("start", set(["start"]))]
ended = 0
while len(queue) > 0:
position, visited = queue.pop()
if position == "end":
ended += 1
else:
for neighbour in graph[position]:
didnt_visit = neighbour not in visited
allowed = neighbour[0].isupper() or didnt_visit
if allowed:
next_visited = visited.copy()
next_visited.add(neighbour)
queue.append((neighbour, next_visited))
return ended
def paths_special(graph):
queue = [("start", set(["start"]), False)]
ended = 0
while len(queue) > 0:
position, visited, walked_twice = queue.pop()
if position == "end":
ended += 1
else:
for neighbour in graph[position]:
didnt_visit = neighbour not in visited
allowed = neighbour[0].isupper() or didnt_visit
allowed_special = not walked_twice and neighbour != "start"
if allowed or allowed_special:
next_walked_twice = walked_twice or not allowed
next_visited = visited.copy()
next_visited.add(neighbour)
queue.append((neighbour, next_visited,
next_walked_twice))
return ended
def part1(text):
parsed = parse(text)
return paths(parsed)
def part2(text):
parsed = parse(text)
return paths_special(parsed)
def main(text):
print("Part1:", part1(text))
print("Part2:", part2(text))
print("==== EXAMPLES ====")
main(example)
print("==== SOLUTION RESULT ====")
main(text)