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) |
这题的解法比较有技巧性,因为不同于其他的动态规划题的需求。
大多数动态规划题要求某单一特征取最值,比如求左上角到右下角的最大/最小步数等,但是这道题目不止要求取最值,还要求中间步骤满足一定的要求,因此常规解法并不能满足要求。
(无后效性:即某阶段状态一旦确定,就不受这个状态以后决策的影响。也就是说,某状态以后的过程不会影响以前的状态,只与当前状态有关。)
因此考虑反着来:
两个步骤中哪个要的少就往哪个方向走,而不是传统的哪个方向给的多就往哪个方向走(这样导致当前最优而不是全局最优)。
Solution
class Solution {
public int calculateMinimumHP(int[][] dungeon) {
if (dungeon == null || dungeon.length == 0 || dungeon[0].length == 0) return 0;
int m = dungeon.length;
int n = dungeon[0].length;
int[][] dp = new int[m][n];
dp[m-1][n-1] = Math.max(1 - dungeon[m-1][n-1], 1);
for (int i = m-2; i >= 0; i--){
dp[i][n-1] = Math.max(dp[i+1][n-1] - dungeon[i][n-1], 1);
}
for (int j = n-2; j >= 0; j--){
dp[m-1][j] = Math.max(dp[m-1][j+1] - dungeon[m-1][j], 1);
}
for (int i = m-2; i >= 0; i--){
for (int j = n-2; j >= 0; j--){
dp[i][j] = Math.min(Math.max(dp[i][j+1] - dungeon[i][j], 1), Math.max(dp[i+1][j] - dungeon[i][j], 1));
}
}
return dp[0][0];
}
}