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.
public int calculateMinimumHP(int[][] dungeon)
{
m = dungeon.length;
n = dungeon[0].length;
dfs(0, 0, 0, dungeon, Integer.MAX_VALUE);
return min;
}
private void dfs(int i, int j, int sum, int[][] dungeon, int curminsum)
{
sum += dungeon[i][j];
curminsum = Math.min(curminsum, sum);
if (i == m - 1 && j == n - 1)
{
if (curminsum >= 0)
min = 1;
else
{
min = Math.min(min, -curminsum + 1);
}
return;
}
if (i < m - 1)
dfs(i + 1, j, sum, dungeon, curminsum);
if (j < n - 1)
dfs(i, j + 1, sum, dungeon, curminsum);
}
1 | -3 | 3 |
0 | -2 | 0 |
-3 | -3 | -3 |
1 | -2 | 1 |
1 | -1(-4) | -1(1) |
-2 | -4 | -4(-2) |
1 | 3 | 3 |
1 | 2(5) | 2(3) |
3 | 5 | 5(3) |
解题思路
一看就是典型的动态规划问题,不过这道题从左上角开始递推不好推,因为要考虑两个因素,一是剩余的血越多越好(血量多可以使得以后的路程中血量更加高一点),行进过程中血量最低值越高越好(这个直接影响到结果),这两个因素都要考虑,且相互影响。其实我们可以从右下角开始推,dp表示如果从该格子出发,最少要多少初始血量。
public int calculateMinimumHP(int[][] dungeon)
{
int m = dungeon.length;
int n = dungeon[0].length;
int[][] ans = new int[m][n];
ans[m - 1][n - 1] = dungeon[m - 1][n - 1] > 0 ? 0: -dungeon[m - 1][n - 1];
for (int i = m - 2; i >= 0; i--)
{
ans[i][n - 1] = dungeon[i][n - 1] >= ans[i + 1][n - 1] ? 0
: ans[i + 1][n - 1] - dungeon[i][n - 1];
}
for (int j = n - 2; j >= 0; j--)
{
ans[m - 1][j] = dungeon[m - 1][j] >= ans[m - 1][j + 1] ? 0
: ans[m - 1][j + 1] - dungeon[m - 1][j];
}
for (int i = m - 2; i >= 0; i--)
for (int j = n - 2; j >= 0; j--)
{
int down = dungeon[i][j] >= ans[i + 1][j] ? 0 : ans[i + 1][j]
- dungeon[i][j];
int right = dungeon[i][j] >= ans[i][j + 1] ? 0 : ans[i][j + 1]
- dungeon[i][j];
ans[i][j] = Math.min(down, right);
}
return ans[0][0] + 1;
}