|
2 | 2 | * @param {number[][]} dungeon
|
3 | 3 | * @return {number}
|
4 | 4 | */
|
5 |
| -const calculateMinimumHP = function(dungeon) { |
6 |
| - if(dungeon.length === 0) return 1 |
7 |
| - const rows = dungeon.length |
8 |
| - const cols = dungeon[0].length |
9 |
| - |
10 |
| - for(let i = rows - 1 ; i >= 0; i--) { |
11 |
| - for(let j = cols - 1; j >= 0; j--) { |
12 |
| - if(i==rows-1 && j==cols-1) dungeon[i][j]=Math.max(1, 1-dungeon[i][j]); |
13 |
| - else if(i==rows-1) dungeon[i][j]=Math.max(1, dungeon[i][j+1]-dungeon[i][j]); |
14 |
| - else if(j==cols-1) dungeon[i][j]=Math.max(1, dungeon[i+1][j]-dungeon[i][j]); |
15 |
| - else dungeon[i][j]=Math.max(1, Math.min(dungeon[i+1][j], dungeon[i][j+1])-dungeon[i][j]); |
| 5 | +const calculateMinimumHP = function (dungeon) { |
| 6 | + const M = dungeon.length |
| 7 | + const N = dungeon[0].length |
| 8 | + // hp[i][j] represents the min hp needed at position (i, j) |
| 9 | + // Add dummy row and column at bottom and right side |
| 10 | + const hp = Array.from({ length: M + 1 }, () => |
| 11 | + Array(N + 1).fill(Number.MAX_VALUE) |
| 12 | + ) |
| 13 | + hp[M][N - 1] = 1 |
| 14 | + hp[M - 1][N] = 1 |
| 15 | + for (let i = M - 1; i >= 0; i--) { |
| 16 | + for (let j = N - 1; j >= 0; j--) { |
| 17 | + const need = Math.min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j] |
| 18 | + hp[i][j] = need <= 0 ? 1 : need |
16 | 19 | }
|
17 | 20 | }
|
18 |
| - return dungeon[0][0] |
19 |
| -}; |
| 21 | + return hp[0][0] |
| 22 | +} |
| 23 | + |
20 | 24 |
|
21 | 25 | // another
|
22 | 26 |
|
|
0 commit comments