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.
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) |
Notes:
- 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.
dp[i][j] 表示从i行j列到最后一个牢房,所需的最少初试血值!
dp[i][j] 可由dp[i + 1][j] 和 dp[i][j +1]推得,
考虑从dp[i+1][j] 推,
- 如果下一步dp[i+1][j]最少需要的初始血值,小于当前格子能添加的血量,
则最少只要能活着进[i,j]格子就可以,即初始为1即可,如果
- 如果dp[i + 1][j] 大于当前格子能添加的血量,则初始血量最少应该能够加上当前格子的血量后,
能够满足进入下一个格子dp[i + 1][j]的初始值即可,即 dp[i][j] = dp[i + 1][j] - grid[i][j];
class Solution {
public:
int rows,cols;
int calculateMinimumHP(vector<vector<int> > &dungeon) {
if(!dungeon.size() || !dungeon[0].size())return 0;
rows = dungeon.size();
cols = dungeon[0].size();
vector<vector<int> >dp;
vector<int>v;
for(int i = 0; i < rows; i++)
{
v.clear();
for(int i = 0; i < cols; i++)
v.push_back(INT_MAX);
dp.push_back(v);
}
int r = mini(0,0,dp,dungeon);
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < cols; j++)
cout<<dp[i][j]<<" ";
cout<<endl;
}
return r;
}
int mini(int r, int c, vector<vector<int> > &dp, vector<vector<int> > &d)
{
if(dp[r][c] != INT_MAX)return dp[r][c];
//注意 下标从0开始, 最后一行是row - 1 不是row
if(r == rows - 1&& c == cols - 1)
{
dp[r][c] = (d[r][c] >= 0 ? 1 : 1 - d[r][c]);
return dp[r][c];
}
int rst = INT_MAX;
if(c < cols - 1)
{
int rtv = mini(r, c + 1, dp, d);
rst = min(rst, d[r][c] >= rtv ? 1 : rtv - d[r][c]);
}
//rst = min(rst, (d[r][c] >= mini(r, c + 1, dp, d) ? 1 : dp[r][c + 1] - d[r][c]));
if(r < rows - 1)
{
int rtv = mini(r + 1, c, dp, d);
rst = min(rst, d[r][c] >= rtv ? 1 : rtv - d[r][c]);
}
//rst = min(rst, (d[r][c] >= mini(r + 1, c, dp, d) ? 1 : dp[r + 1][c] - d[r][c]));
//最后的结果要保存,老忘
dp[r][c] = rst;
return rst;
}
};