Advertisement
nikunjsoni

174

May 21st, 2021
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.67 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int calculateMinimumHP(vector<vector<int>>& dungeon) {
  4.         int m = dungeon.size();
  5.         int n = dungeon[0].size();
  6.         // hp[i][j] represents the min hp needed at position (i, j)
  7.         // Add dummy row and column at bottom and right side
  8.         vector<vector<int> > hp(m + 1, vector<int>(n + 1, INT_MAX));
  9.         hp[m][n - 1] = 1;
  10.         hp[m - 1][n] = 1;
  11.         for(int i = m - 1; i >= 0; i--){
  12.             for(int j = n - 1; j >= 0; j--){
  13.                 int need = min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j];
  14.                 hp[i][j] = need <= 0 ? 1 : need;
  15.             }
  16.         }
  17.         return hp[0][0];
  18.     }
  19. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement