Skip to content

Commit 02d6404

Browse files
committed
Add solution to 2024-12-15
1 parent 7ab4578 commit 02d6404

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

2024/day15/solutions.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
with open("input") as f:
2+
ls, moves = f.read().strip().split("\n\n")
3+
4+
dirs = {"^": -1, "v": 1, "<": -1j, ">": 1j}
5+
moves = list(map(dirs.__getitem__, moves.replace("\n", "")))
6+
board = {i + 1j * j: x for i, l in enumerate(ls.split("\n")) for j, x in enumerate(l)}
7+
8+
9+
def solve(part2):
10+
walls = {z for z, x in board.items() if x == "#"}
11+
boxes = {z for z, x in board.items() if x == "O"}
12+
robot = next(z for z, x in board.items() if x == "@")
13+
if part2:
14+
walls = {w.real + 2 * w.imag * 1j for w in walls}
15+
walls |= {z + 1j for z in walls}
16+
boxes = {b.real + 2 * b.imag * 1j for b in boxes}
17+
robot = robot.real + 2 * robot.imag * 1j
18+
for dz in moves:
19+
to_move = set()
20+
to_check = [robot + dz]
21+
while to_check:
22+
z = to_check.pop()
23+
if z in boxes or (part2 and z - 1j in boxes):
24+
to_move.add(z)
25+
to_check.append(z + dz)
26+
if part2 and dz.real:
27+
other = z + 1j if z in boxes else z - 1j
28+
to_move.add(other)
29+
to_check.append(other + dz)
30+
elif z in walls:
31+
break
32+
else:
33+
to_move = to_move & boxes
34+
boxes -= to_move
35+
boxes |= {w + dz for w in to_move}
36+
robot += dz
37+
return sum(z.real * 100 + z.imag for z in boxes)
38+
39+
40+
# Part 1
41+
print(solve(False))
42+
43+
# Part 2
44+
print(solve(True))

0 commit comments

Comments
 (0)