class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dungeon) {
int m = dungeon.size()  1;
int n = dungeon[0].size()  1;
dungeon[m][n] = dungeon[m][n]>0 ? 0 : dungeon[m][n];
for (int i = m; i >= 0; i) {
for (int j = n; j >= 0; j) {
if (i < m && j < n)
dungeon[i][j] = max(dungeon[i + 1][j], dungeon[i][j + 1]) + dungeon[i][j];
else if (i < m)
dungeon[i][j] = dungeon[i + 1][j] + dungeon[i][j];
else if (j < n)
dungeon[i][j] = dungeon[i][j + 1] + dungeon[i][j];
dungeon[i][j] = dungeon[i][j] > 0 ? 0 : dungeon[i][j];
}
}
return dungeon[0][0] > 0 ? 1 : abs(dungeon[0][0]) + 1;
}
};
Simple C++ Solution with O(1) space complexity


Each element of dungeon[][] after running this function indicates how much HP is needed to get bottomright. If dungeon[i][j] is larger than 0, this means that we don't need additional HP from dungeon[i][j] to bottomright. That's why I set 0 to dungeon[i][j] when it is larger than 0.