Skip to content

Commit 71e4578

Browse files
committed
Dungeon Game: DP & Greedy, start from the P, keep the health no higher than zero.
1 parent 42ab0bd commit 71e4578

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Hard/174_Dungeon-Game.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#include "../Header.h"
2+
3+
using namespace std;
4+
int calculateMinimumHP(vector<vector<int>>& dungeon) {
5+
int h = dungeon.size(), w = dungeon[0].size();
6+
int **base = new int*[h];
7+
for (int i = 0; i < h; i++) base[i] = new int[w];
8+
9+
base[h-1][w-1] = dungeon[h-1][w-1] >= 0 ? 0 : -dungeon[h-1][w-1];
10+
for (int i = h-2; i >= 0; i--) {
11+
base[i][w-1] = base[i+1][w-1] - dungeon[i][w-1];
12+
if (base[i][w-1] < 0) base[i][w-1] = 0;
13+
14+
}
15+
for (int i = w-2; i >=0; i--) {
16+
base[h-1][i] = base[h-1][i+1] - dungeon[h-1][i];
17+
if (base[h-1][i] < 0) base[h-1][i] = 0;
18+
}
19+
20+
for (int i = h-2; i >= 0; i--) {
21+
for (int j = w-2; j >= 0; j--) {
22+
base[i][j] = min(base[i+1][j], base[i][j+1]) - dungeon[i][j];
23+
if (base[i][j] < 0) base[i][j] = 0;
24+
}
25+
}
26+
27+
return base[0][0] + 1;
28+
}
29+

0 commit comments

Comments
 (0)