Skip to content

Instantly share code, notes, and snippets.

@RP-3
Created February 24, 2020 09:49
Show Gist options
  • Save RP-3/e1091c4279abc6fba1074cb08658bcab to your computer and use it in GitHub Desktop.
Save RP-3/e1091c4279abc6fba1074cb08658bcab to your computer and use it in GitHub Desktop.
// recursive
var calculateMinimumHP = function(dungeon) {
const [m, n] = [dungeon.length, dungeon[0].length];
const dp = new Array(m).fill(0).map(() => new Array(n).fill(null));
const traverse = (i, j) => {
if(i === m) return Infinity;
if(j === n) return Infinity;
if(i === m-1 && j === n-1){
const squareCost = dungeon[m-1][n-1];
return squareCost <= 0 ? Math.abs(squareCost) + 1 : 1;
}
if(dp[i][j] !== null) return dp[i][j];
return dp[i][j] = Math.max(
Math.min(
traverse(i, j+1) - dungeon[i][j], // health requirement to get from right to here
traverse(i+1, j) - dungeon[i][j] // health requirement to get from down to here
),
1 // because our health can never be below 1
);
};
return traverse(0, 0);
};
// bottom-up
var calculateMinimumHP = function(dungeon) {
const [m, n] = [dungeon.length, dungeon[0].length];
const dp = new Array(m).fill(0).map(() => new Array(n).fill(null));
const squareCost = dungeon[m-1][n-1];
dp[m-1][n-1] = squareCost <= 0 ? Math.abs(squareCost) + 1 : 1;
for(let i=m-2; i>=0; i--){
const lastCol = n-1;
dp[i][lastCol] = Math.max(dp[i+1][lastCol] - dungeon[i][lastCol], 1);
}
for(let i=n-2; i>=0; i--){
const lastRow = m-1;
dp[lastRow][i] = Math.max(dp[lastRow][i+1] - dungeon[lastRow][i], 1);
}
for(let i=m-2; i>=0; i--){
for(let j=n-2; j>=0; j--){
dp[i][j] = Math.max(Math.min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j], 1);
}
}
return dp[0][0];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment