8000 Add solution to 2023-12-17 · fuglede/adventofcode@c9acf8a · GitHub
[go: up one dir, main page]

Skip to content

Commit c9acf8a

Browse files
committed
Add solution to 2023-12-17
1 parent 6adb945 commit c9acf8a

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

2023/day17/solutions.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from collections import defaultdict
2+
from heapq import heappop, heappush
3+
from itertools import count
4+
from math import inf
5+
6+
with open("input") as f:
7+
ls = f.read().strip().split("\n")
8+
9+
board = {i + 1j * j: int(x) for i, l in enumerate(ls) for j, x in enumerate(l)}
10+
N, M = len(ls), len(ls[0])
11+
12+
13+
def solve(part2):
14+
q = [(0, 0, 0, 0, 0)]
15+
best = defaultdict(lambda: inf)
16+
c = count()
17+
while q:
18+
dist, _, z, last_dz, dz_count = heappop(q)
19+
if z == N - 1 + 1j * (M - 1) and (not part2 or dz_count >= 4):
20+
return dist
21+
for dz in (1, -1, 1j, -1j):
22+
if dz == -last_dz:
23+
continue
24+
if part2 and last_dz and dz != last_dz and dz_count < 4:
25+
continue
26+
if dz == last_dz:
27+
this_dz_count = dz_count + 1
28+
if this_dz_count == (11 if part2 else 4):
29+
continue
30+
else:
31+
this_dz_count = 1
32+
w = z + dz
33+
if w in board:
34+
new_dist = dist + board[w]
35+
if new_dist >= best[w, dz, this_dz_count]:
36+
continue
37+
best[w, dz, this_dz_count] = new_dist
38+
heappush(q, (new_dist, next(c), w, dz, this_dz_count))
39+
40+
41+
print(solve(False))
42+
print(solve(True))

0 commit comments

Comments
 (0)
0