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.
int min(int a, int b) {
return a < b ? a : b;
}
int max(int a, int b) {
return a > b ? a : b;
}
int calculateMinimumHP(int** dungeon, int dungeonRowSize, int dungeonColSize) {
int dp[dungeonRowSize][dungeonColSize];
dp[dungeonRowSize - 1][dungeonColSize - 1] = dungeon[dungeonRowSize - 1][dungeonColSize - 1] >= 0 ? 1 : abs(dungeon[dungeonRowSize - 1][dungeonColSize - 1]) + 1;
int i, j;
int need;
for (i = dungeonRowSize - 2; i >= 0; --i) {
need = dp[i + 1][dungeonColSize - 1] - dungeon[i][dungeonColSize - 1];
dp[i][dungeonColSize - 1] = need <= 0 ? 1 : need;
}
for (j = dungeonColSize - 2; j >= 0; --j) {
need = dp[dungeonRowSize - 1][j + 1] - dungeon[dungeonRowSize - 1][j];
dp[dungeonRowSize - 1][j] = need <= 0 ? 1 : need;
}
int min_inds = dungeonRowSize < dungeonColSize ? dungeonRowSize : dungeonColSize;
int inds;
for (inds = 2; inds <= min_inds; ++inds) {
i = dungeonRowSize - inds;
j = dungeonColSize - inds;
for (; i >= 0; --i) {
dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
}
i = dungeonRowSize - inds;
for (--j; j >= 0; --j) {
dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
}
}
return dp[0][0];
}
学习笔记:
1. 这是一个动态问题
2. 假设K从(i, j)到P的位置需要dp[i, j]则 dp[i, j] = max(1, min(dp[i + 1, j], dp[i, j + 1]) - dungeon[i, j])
3. min(dp[i + 1, j], dp[i, j + 1]) - dungeon[i, j] = 需要的能量
4. 需要的能量 <= 0 说明 K来之前是活的就可以即dp[i, j] = 1, 否则dp[i, j] = 需要的能量(即能满足来之前是活的,走到(i, j)是活的,继续往下走也是活的)