Skip to content

Commit 6426abf

Browse files
authored
Update 174-dungeon-game.js
1 parent 1a27d71 commit 6426abf

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed

174-dungeon-game.js

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,25 @@
22
* @param {number[][]} dungeon
33
* @return {number}
44
*/
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
1619
}
1720
}
18-
return dungeon[0][0]
19-
};
21+
return hp[0][0]
22+
}
23+
2024

2125
// another
2226

0 commit comments

Comments
 (0)