AoC 2021 D23: Amphipod
| Problem statement | Source code | Tags: Dijkstra
← Previous Back to AoC Index Next →
While this problem doesn't look graph-y on the surface, essentially we have a state space and a set of transitions between states with associated costs, so we can use Dijkstra's to find the minimum-cost path from the initial state to the goal state.
The first tricky part might be parsing the input. I represented the state as { rooms: number[][], hallway: (number | undefined)[] }, where rooms[i] is the stack of amphipods in room i (rooms[i][0] is the one closest to the hallway), and hallway[j] is the amphipod (or undefined if empty) at hallway position j. Amphipods are represented as numbers 0-3.
I already have template code from day 15, which translates directly:
The rest is a matter of implementing the transition function, nextStates(). There are two types of moves: moving an amphipod from a room to the hallway, and moving an amphipod from the hallway to a room.
To move an amphipod from a room to the hallway, we iterate through the rooms. If the room is empty or already good (i.e., contains only amphipods of the correct type), we skip it. Otherwise, we take the top amphipod, and enumerate all hallway positions it can move to (i.e., all positions to the left and right until we hit a wall or another amphipod, and skip positions right outside rooms). The distance is the horizontal distance plus the vertical distance to get out of the room.
To move an amphipod from the hallway to a room, we iterate through pods in the hallway. If the pod cannot move to the target room because its path is blocked or the room contains incorrect amphipods, we skip it. Otherwise, we compute the distance and create the new state.
Part 2 just requires changing the initial rooms to insert the extra amphipods.