class Solution {
public int calculateMinimumHP(int[][] dungeon) {
int rows = dungeon.length;
int cols = dungeon[0].length;
int[][] dp = new int[rows][cols]; // dp[i][j] 为进入 dungeon[i][j] 所需要的最小血量以通过 dungeon[i][j] 以及后续 dungeon
dp[rows - 1][cols - 1] = Math.max(1, 1 - dungeon[rows - 1][cols - 1]);
// last column
for (int i = rows - 2; i >= 0; i--) {
dp[i][cols - 1] = Math.max(1, dp[i + 1][cols - 1] - dungeon[i][cols - 1]);
}
// last row
for (int i = cols - 2; i >= 0; i--) {
dp[rows - 1][i] = Math.max(1, dp[rows - 1][i + 1] - dungeon[rows - 1][i]);
}
for (int i = rows - 2; i >= 0; i--) {
for (int j = cols - 2; j >= 0; j--) {
int right = Math.max(1, dp[i][j + 1] - dungeon[i][j]);
int down = Math.max(1, dp[i + 1][j] - dungeon[i][j]);
dp[i][j] = Math.min(right, down);
}
}
return dp[0][0];
}
}
网友评论