Public
Edited
Dec 2, 2024
Paused
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parse(input) {
return input.split("\n").map((row) => row.split("").map(Number));
}
Insert cell
Insert cell
function dirOffsets(dir) {
switch (dir) {
case "EW":
return [
[0, 1],
[0, -1]
];
case "NS":
return [
[1, 0],
[-1, 0]
];
}
}
Insert cell
Insert cell
function minHeatLoss(grid, maxSteps = 3, minSteps = 1) {
const hash = ([r, c, dir]) => `${r},${c}${dir}`;
const [nRows, nCols] = [grid.length, grid[0].length];
const visited = new Set();
const queue = new PQ((a, b) => b[0] > a[0]);

// Consider all the moves at 90 degrees to previous movement.
const addMoves = (hl, row, col, dir) => {
for (const [dRow, dCol] of dirOffsets(dir)) {
let hl2 = hl;
for (let i = 1; i <= maxSteps; i++) {
const [r, c] = [row + i * dRow, col + i * dCol];
if (r >= 0 && r < nRows && c >= 0 && c < nCols) {
hl2 += grid[r][c];
if (i >= minSteps) {
queue.add([hl2, r, c, dir === "EW" ? "NS" : "EW"]);
}
}
}
}
};

// Start in top-left corner with two possible initial movement directions
queue.add([0, 0, 0, "EW"]);
queue.add([0, 0, 0, "NS"]);

while (!queue.isEmpty()) {
const [heatLoss, row, col, dir] = queue.poll();
if (row === nRows - 1 && col === nCols - 1) {
// We've found the destination!
return heatLoss;
}
const state = hash([row, col, dir]);
if (!visited.has(state)) {
visited.add(state); // Log this visit so we don't return here.
addMoves(heatLoss, row, col, dir); // Where can we go from here?
}
}
}
Insert cell
function part1(input) {
return minHeatLoss(parse(input));
}
Insert cell
Insert cell
Insert cell
Insert cell
function part2(input) {
return minHeatLoss(parse(input), 10, 4);
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more