从底往上,注意必须保证他有1滴血。
public class Solution {
public int calculateMinimumHP(int[][] dungeon) {
int rows = dungeon.length;
int cols = dungeon[0].length;
if(rows == 0&&cols ==0)
return 0;
int[][]dp = new int[dungeon.length][dungeon[0].length];
int max=-99999999;
for(int i=rows-1;i>=0;i--){
for(int j=cols-1;j>=0;j--){
if(i==rows-1&&j==cols-1){
dp[i][j] = Math.max(1-dungeon[i][j],1);
continue;
}
if(j==cols-1){
dp[i][j] = Math.max(dp[i+1][j]-dungeon[i][j],1);
}else if(i==rows-1){
dp[i][j] = Math.max(dp[i][j+1]-dungeon[i][j],1);
}else{
int right = Math.max(dp[i][j+1]-dungeon[i][j],1);
int down = Math.max(dp[i+1][j]-dungeon[i][j],1);
dp[i][j] = Math.min(right,down);
}
}
}
if(dp[0][0]<=0)return 1;
return dp[0][0];
}
}