|
| 1 | +//https://leetcode.com/problems/dungeon-game/ |
| 2 | +////Difficulty Level: Hard |
| 3 | +//Tags: Dynamic Programming |
| 4 | +//Time complexity: O(m*n) |
| 5 | +//Space complexity: O(m*n) |
| 6 | +//bottom-up DP approach |
| 7 | +class Solution |
| 8 | +{ |
| 9 | + public: |
| 10 | + int calculateMinimumHP(vector<vector<int>>& dungeon) |
| 11 | + { |
| 12 | + int m = dungeon.size(); |
| 13 | + if(r==0) //empty dungeon |
| 14 | + return 0; |
| 15 | + |
| 16 | + int n = dungeon[0].size(); |
| 17 | + |
| 18 | + //dp[i][j] --> min health req to reach the princess with starting cell as (i,j) -1 |
| 19 | + vector<vector<int> > dp(r, vector<int>(c)); |
| 20 | + |
| 21 | + for (int i = m-1; i>=0; i--) //traversing the array from bottom |
| 22 | + { |
| 23 | + for (int j = n-1; j>=0; j--) |
| 24 | + { |
| 25 | + //if starting from last cell, |
| 26 | + //if value at last cell is -ve, health req. is 1+abs(value) |
| 27 | + //if value at last cell is +ve, health req. is 0+1 |
| 28 | + if (i == m-1 && j == n-1) |
| 29 | + { |
| 30 | + dp[i][j] = min(0, dungeon[i][j]); |
| 31 | + } |
| 32 | + |
| 33 | + //if starting from last row, |
| 34 | + //total health req. is sum of curr cell value and health req. at next cell |
| 35 | + //if the sum is +ve, health req. is 0+1 |
| 36 | + //if the sum is -ve, health req. is 1+abs(sum) |
| 37 | + else if (i == m-1) |
| 38 | + { |
| 39 | + dp[i][j] = min(0, dungeon[i][j]+dp[i][j+1]); |
| 40 | + } |
| 41 | + |
| 42 | + //if starting from last column, |
| 43 | + //total health req. is sum of curr cell value and health req. at next cell |
| 44 | + //if the sum is +ve, health req. is 0+1 |
| 45 | + //if the sum is -ve, health req. is 1+abs(sum) |
| 46 | + else if (j == n-1) |
| 47 | + { |
| 48 | + dp[i][j] = min(0, dungeon[i][j]+dp[i+1][j]); |
| 49 | + } |
| 50 | + |
| 51 | + //if starting from any other cell, |
| 52 | + //make a choice to go to the cell with less req. health(more positive dp value) after the curr cell |
| 53 | + //the req. health is either 0 or sum of the curr cell value and health req. at next chosen cell |
| 54 | + else |
| 55 | + { |
| 56 | + dp[i][j] = min(0, dungeon[i][j]+max(dp[i][j+1],dp[i+1][j])); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + //actual starting point is (0,0), so return abs(dp(0,0))+1 |
| 61 | + //1 is added because the knight needs to have atleast 1 health to survive, else he will die |
| 62 | + return abs(dp[0][0])+1; |
| 63 | + } |
| 64 | +}; |
0 commit comments