Skip to content
advent of code 2021

day 15

chiton

approach

the lowest-risk path from the top-left to the bottom-right corner is a shortest-path problem on a grid where entering a cell costs its risk level. the solution runs dijkstra with a binary heap, relaxing the four neighbours of each cell.

for part 2 the map is tiled 5×5, with each copy's risk going up by one per tile and wrapping from 9 back to 1. the code builds that larger grid explicitly, extending rows first and then appending rows, and runs the same dijkstra on it.

the trick

it's plain dijkstra; part 2 only changes the grid, not the algorithm.

python
def solve(grid):
    dists = defaultdict(lambda: inf)
    h = [(0, 0, 0)]
    while h:
        w, r, c = heappop(h)
        for nr, nc in neighbors(grid, r, c):
            if (nw := w + grid[nr][nc]) < dists[(nr, nc)]:
                dists[(nr, nc)] = nw
                heappush(h, (nw, nr, nc))
    return dists[(len(grid) - 1, len(grid[0]) - 1)]