题目
The demons had captured the princess § 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.
For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
-2 (K) | -3 | 3 |
-5 | -10 | 1 |
10 | 30 | -5 ( P ) |
Note:
The knight’s health has no upper bound.
Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
思路
这道题明显就是一道动态规划的题目。我们设
f
(
i
,
j
)
f(i,j)
f(i,j)为走到地牢的[i,j]位置时,所需的最小生命值(已计算进入[i,j]的生命变化)。我们知道,最右下角的房间所需的最小生命值为1(活着),接着从这里出发,很容易地回推骑士到达前面的房间时所需的最小生命值。我们有递推式:
f
(
i
,
j
)
=
{
1
,
i
=
m
−
1
,
j
=
n
−
1
m
i
n
(
h
p
D
,
h
p
R
)
,
h
p
D
=
m
a
x
{
f
(
i
+
1
,
j
)
−
d
(
i
+
1
,
j
)
,
1
}
h
p
R
=
m
i
n
{
f
(
i
,
j
+
1
)
−
d
(
i
,
j
+
1
)
,
1
}
f(i,j)=\left\{ \begin{array}{} \begin{aligned} 1, &\quad i=m-1,j=n-1 \\ min(hpD, hpR),&\quad hpD= max\{f(i+1,j)-d(i+1,j), 1\}\\ &\quad hpR=min\{f(i,j+1)-d(i,j+1),1\} \\ \end{aligned} \end{array} \right.
f(i,j)=⎩⎪⎨⎪⎧1,min(hpD,hpR),i=m−1,j=n−1hpD=max{f(i+1,j)−d(i+1,j),1}hpR=min{f(i,j+1)−d(i,j+1),1}
上式中,若hpDown或hpRight对应的位置不存在,那么把对应变量设作INT_MAX。所求的初始最小生命值为
m
a
x
{
f
(
0
,
0
)
−
d
(
0
,
0
)
,
1
}
max\{f(0,0)-d(0,0), 1\}
max{f(0,0)−d(0,0),1}
代码
class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dungeon) {
int m = dungeon.size();
int n = dungeon[0].size();
vector<vector<int>> needHealth(m, vector<int>(n, INT_MAX));
for(int i = m - 1; i >= 0; --i) {
for(int j = n - 1; j >= 0; --j) {
int hpDown = INT_MAX;
int hpRight = INT_MAX;
if(i + 1 < m) {
hpDown = needHealth[i + 1][j] - dungeon[i + 1][j];
}
if(j + 1 < n) {
hpRight = needHealth[i][j + 1] - dungeon[i][j + 1];
}
needHealth[i][j] = min(hpDown, hpRight);
if(needHealth[i][j] < 1 || needHealth[i][j] == INT_MAX) {
needHealth[i][j] = 1;
}
}
}
return max(1, needHealth[0][0] - dungeon[0][0]);
}
};