174. Dungeon Game
// Dynamic Programming
// Use max(1, ...) to protect the minimum hp to be 1
int calculateMinimumHP(vector<vector<int>>& dungeon) { // time: O(m*n); space: O(m*n)
int m = dungeon.size(), n = dungeon[0].size();
vector<vector<int> > hp(m, vector<int>(n, 0));
// initialization
hp[m - 1][n - 1] = max(1, 1 - dungeon[m - 1][n - 1]);
for (int i = m - 2; i >= 0; --i) {
hp[i][n - 1] = max(1, hp[i + 1][n - 1] - dungeon[i][n - 1]);
}
for (int j = n - 2; j >= 0; --j) {
hp[m - 1][j] = max(1, hp[m - 1][j + 1] - dungeon[m - 1][j]);
}
for (int i = m - 2; i >= 0; --i) {
for (int j = n - 2; j >= 0; --j) {
hp[i][j] = max(1, min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j]);
}
}
return hp.front().front();
}Last updated