每日leetcode-174

174. Dungeon Game

The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.

The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.

Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0’s) or contain magic orbs that increase the knight’s health (positive integers).

In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.

Write a function to determine the knight’s minimum initial health so that he is able to rescue the princess.

就是从左上到右下,HP会加上格子里面的数,HP不能<=0,求初始HP最少是多少。

刚开始想要从左上到右下正常dp,记录一下当前的 HP减少量 和 HP最优路径中临界值,但是如果:

  • 到同一个格子的两条路,一条当前HP减少量最少,另外一条HP最优路径中临界值更少,那应该选哪一条?怎么更新?

所以看了网上的解释,直接从结果往回走进行dp即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
int myMin(int a, int b) {
return a < b ? a : b;
}

int myMax(int a, int b) {
return a > b ? a : b;
}

int calculateMinimumHP(vector<vector<int>>& dungeon) {
int h = dungeon.size();
if (h == 0) {
return 1;
}
int w = dungeon[0].size();
if (w == 0) {
return 1;
}
vector<vector<int>> data(h, vector<int>(w, 0));
data[h - 1][w - 1] = myMax(1, 1 - dungeon[h - 1][w - 1]);
int i, j;
i = h - 1;
for (j = w - 2; j >= 0; j--) {
data[i][j] = myMax(1, data[i][j + 1] - dungeon[i][j]);
}
j = w - 1;
for (i = h - 2; i >= 0; i--) {
data[i][j] = myMax(1, data[i + 1][j] - dungeon[i][j]);
}
for (i = h - 2; i >= 0; i--) {
for (j = w - 2; j >= 0; j--) {
data[i][j] = myMin(myMax(1, data[i][j + 1] - dungeon[i][j]), myMax(1, data[i + 1][j] - dungeon[i][j]));
}
}
return data[0][0];
}
};