-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday18.py
More file actions
executable file
·69 lines (57 loc) · 1.84 KB
/
Copy pathday18.py
File metadata and controls
executable file
·69 lines (57 loc) · 1.84 KB
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
from collections import deque
from aoc_utils import * # type: ignore
from aocd import get_data
data = get_data(year=2024, day=18, block=True)
GRID_SIZE = 71
def part_one(data):
grid = Grid([["." for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)])
for i, line in enumerate(data.splitlines()):
if i == 1024:
break
x, y = ints(line)
grid[y, x] = "#"
graph = Graph()
queue = deque([(0, 0)])
history = set()
while queue:
yx = queue.popleft()
if yx in history:
continue
history.add(yx)
for nyx, c in grid.around_with_index(yx, corners=False):
if c != "#":
queue.append(nyx)
graph.add_edge(yx, nyx)
graph.add_edge(nyx, yx)
dij = graph.dijkstra((0, 0))
return dij.distance_to((GRID_SIZE - 1, GRID_SIZE - 1))
def part_two(data):
grid = Grid([["." for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)])
graph = Graph()
queue = deque([(0, 0)])
history = set()
while queue:
yx = queue.popleft()
if yx in history:
continue
history.add(yx)
for nyx, _ in grid.around_with_index(yx, corners=False):
queue.append(nyx)
graph.add_edge(yx, nyx)
graph.add_edge(nyx, yx)
best_path = None
for line in data.splitlines():
x, y = ints(line)
grid[y, x] = "#"
yx = (y, x)
del graph._edges[yx]
for ayx, _ in grid.around_with_index(yx, corners=False):
graph._edges[ayx].discard(yx)
if best_path is None or yx in best_path:
dij = graph.dijkstra((0, 0))
path = dij.path_to((GRID_SIZE - 1, GRID_SIZE - 1))
if path is None:
return yx
best_path = set(path)
print(part_one(data))
print(part_two(data))