-
Notifications
You must be signed in to change notification settings - Fork 0
/
day12.py
63 lines (51 loc) · 1.22 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
from utils import read_day
import queue
def parse_line(line):
return line.split('-')
pairs = read_day(12, parse_line)
graph = {}
for a, b in pairs:
graph.setdefault(a, []).append(b)
graph.setdefault(b, []).append(a)
def part1():
return bfs(graph, 'start')
def bfs(graph, start):
q = queue.Queue()
q.put((start, [start]))
paths = 0
while not q.empty():
curr, visited = q.get()
if curr == 'end':
paths += 1
continue
for n in graph[curr]:
if n not in visited:
v = [x for x in visited]
if not is_big(n):
v.append(n)
q.put((n, v))
return paths
def is_big(cave):
return cave.isupper()
print(f'Part 1: {part1()}')
def part2():
return bfs2(graph, 'start')
def bfs2(graph, start):
q = queue.Queue()
q.put((start, [start], True))
paths = 0
while not q.empty():
curr, visited, can_visit = q.get()
if curr == 'end':
paths += 1
continue
for n in graph[curr]:
if n not in visited:
v = [x for x in visited]
if not is_big(n):
v.append(n)
q.put((n, v, can_visit))
elif n not in ('start', 'end') and can_visit:
q.put((n, visited, False))
return paths
print(f'Part 2: {part2()}')