Skip to content

Instantly share code, notes, and snippets.

@ValeriiVasin
Created June 21, 2020 14:45
Show Gist options
  • Save ValeriiVasin/e81da2cf4b99612bb33197ac09c48897 to your computer and use it in GitHub Desktop.
Save ValeriiVasin/e81da2cf4b99612bb33197ac09c48897 to your computer and use it in GitHub Desktop.
/**
* @param {number[][]} dungeon
* @return {number}
*/
var calculateMinimumHP = function(dungeon) {
const xMax = dungeon[0].length - 1;
const yMax = dungeon.length - 1;
const hp = new Map([
[key(xMax + 1, yMax), 1],
[key(xMax, yMax + 1), 1]
]);
for (let y = yMax; y >= 0; y--) {
for (let x = xMax; x >= 0; x--) {
hp.set(key(x, y), min(dungeon, x, y, hp));
}
}
return get(hp, 0, 0);
};
function min(dungeon, x, y, hp) {
const value = dungeon[y][x];
return Math.max(
1,
Math.min(get(hp, x + 1, y), get(hp, x, y + 1)) - value,
);
}
function get(hp, x, y) {
return hp.get(key(x, y)) ?? Infinity;
}
function key(x, y) {
return `${x},${y}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment