Skip to content

Commit f0556c6

Browse files
committed
Implement 2024 day 16 part 1
1 parent da7ee96 commit f0556c6

File tree

4 files changed

+104
-0
lines changed

4 files changed

+104
-0
lines changed

2024/src/aoc/days/day16.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import heapq
2+
3+
import numpy
4+
5+
from . import SeparateRunner
6+
7+
TURNS = (
8+
(-1, 1),
9+
(1, -1),
10+
)
11+
12+
13+
class DayRunner(SeparateRunner):
14+
@classmethod
15+
def part1(cls, input: str) -> int:
16+
grid = numpy.array([list(line) for line in input.strip().split("\n")])
17+
18+
y, x = numpy.where(grid == "S")
19+
x, y = x[0], y[0]
20+
21+
todo = [(0, x, y, 1, 0)]
22+
best = {
23+
(x, y, 1, 0): 0,
24+
}
25+
26+
def enqueue(dist, x, y, dx, dy):
27+
if grid[y, x] == "#":
28+
return
29+
30+
if (x, y, dx, dy) not in best or best[x, y, dx, dy] > dist:
31+
best[x, y, dx, dy] = dist
32+
heapq.heappush(todo, (dist, x, y, dx, dy))
33+
34+
while todo:
35+
dist, x, y, dx, dy = heapq.heappop(todo)
36+
37+
if best[x, y, dx, dy] < dist:
38+
continue
39+
40+
if grid[y, x] == "E":
41+
return dist
42+
43+
enqueue(dist + 1, x + dx, y + dy, dx, dy)
44+
enqueue(dist + 2001, x - dx, y - dy, dx, dy)
45+
46+
for tx, ty in TURNS:
47+
ndx = dy * ty
48+
ndy = dx * ty
49+
50+
enqueue(dist + 1001, x + ndx, y + ndy, ndx, ndy)
51+
52+
raise ValueError("Did not find path to exit")
53+
54+
@classmethod
55+
def part2(cls, input: str) -> int:
56+
pass

2024/tests/samples/16.1.txt

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
###############
2+
#.......#....E#
3+
#.#.###.#.###.#
4+
#.....#.#...#.#
5+
#.###.#####.#.#
6+
#.#.#.......#.#
7+
#.#.#####.###.#
8+
#...........#.#
9+
###.#.#####.#.#
10+
#...#.....#.#.#
11+
#.#.#.###.#.#.#
12+
#.....#...#.#.#
13+
#.###.#.#.#.#.#
14+
#S..#.....#...#
15+
###############

2024/tests/samples/16.2.txt

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#################
2+
#...#...#...#..E#
3+
#.#.#.#.#.#.#.#.#
4+
#.#.#.#...#...#.#
5+
#.#.#.#.###.#.#.#
6+
#...#.#.#.....#.#
7+
#.#.#.#.#.#####.#
8+
#.#...#.#.#.....#
9+
#.#.#####.#.###.#
10+
#.#.#.......#...#
11+
#.#.###.#####.###
12+
#.#.#...#.....#.#
13+
#.#.#.#####.###.#
14+
#.#.#.........#.#
15+
#.#.#.#########.#
16+
#S#.............#
17+
#################

2024/tests/test_day16.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pytest
2+
3+
from aoc.days.day16 import DayRunner
4+
5+
from . import get_data
6+
7+
8+
@pytest.mark.parametrize(
9+
"data,result",
10+
[
11+
(get_data(16, 1), 7036),
12+
(get_data(16, 2), 11048),
13+
],
14+
)
15+
def test_sample_part1(data: str, result: int) -> None:
16+
assert DayRunner.part1(data) == result

0 commit comments

Comments
 (0)