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]);
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"]);
}
}
}
}
};
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) {
return heatLoss;
}
const state = hash([row, col, dir]);
if (!visited.has(state)) {
visited.add(state);
addMoves(heatLoss, row, col, dir);
}
}
}