Advent of Code 2024 - Day 16Reindeer Maze
| Problem statement | Source code | Tags: MazeDijkstra
This problem pays tribute to 2015 day 14 (unimplemented).
Part 1
We essentially want the shortest path through the maze, where each turning also incurs a cost. So the state is not just the position, but also the reindeer's direction, and a transition is either a turn or a move forward, with different costs.
I then just run Dijkstra's on this state space.
Happy to see that OCaml has a Pqueue module built-in. (Technically I should be using 5.2.1, the version released in 2024, but I cheated and used 5.4.)
Note: we don't stop when we reach the target, because there may be multiple targets that are equally good, and we want all of them to be considered for part 2.
There are 4 possible targets, one for each direction when it reaches the target cell. We take the minimum of those.
It turns out that the optimal target is unique, so theoretically we could have stopped early when we reached ex, ey. But I kept this solution for robustness.
Part 2
Now we need all cells that are on some optimal path. I took a—perhaps unorthodox?—approach of running Dijkstra's again, from the target back to the start. Then for each state, I check if the distance from the start to that state plus the distance from that state to the target equals the optimal distance. If it does, then that cell is on an optimal path.
Again, because in reality there's a single optimal target state, we could have picked that single e state, instead of using loops, but this is more robust.