class Solution {
public int calculateMinimumHP(int[][] dungeon) {
if (dungeon == null || dungeon.length == 0 || dungeon[0].length == 0) {
return 0;
}
int rowSize = dungeon.length;
int colSize = dungeon[0].length;
int[][] dp = new int[rowSize][colSize];
dp[rowSize - 1][colSize -1] = Math.max(0, -dungeon[rowSize - 1][colSize - 1]);
for (int i = rowSize - 2; i >= 0; --i) {
int needMin = dp[i + 1][colSize - 1] - dungeon[i][colSize - 1];
dp[i][colSize -1] = Math.max(0, needMin);
}
for (int i = colSize - 2; i >= 0; --i) {
int needMin = dp[rowSize - 1][i + 1] - dungeon[rowSize - 1][i];
dp[rowSize - 1][i] = Math.max(0, needMin);
}
for (int i = rowSize - 2; i >= 0; --i) {
for (int j = colSize - 2; j >= 0; --j) {
int needMin = Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j];
dp[i][j] = Math.max(0, needMin);
}
}
return dp[0][0] + 1;
}
}
class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dungeon) {
int n = dungeon.size(), m = dungeon[0].size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, INT_MAX));
dp[n][m - 1] = dp[n - 1][m] = 1;
for (int i = n - 1; i >= 0; --i) {
for (int j = m - 1; j >= 0; --j) {
int minn = min(dp[i + 1][j], dp[i][j + 1]);
dp[i][j] = max(minn - dungeon[i][j], 1);
}
}
return dp[0][0];
}
};