| 18 | // Time complexity : O(MN) i.e. the given matrix's dimensions. |
| 19 | |
| 20 | class Solution |
| 21 | { |
| 22 | public: |
| 23 | int calculateMinimumHP(vector<vector<int>> &dungeon) |
| 24 | { |
| 25 | int r = dungeon.size(); // row size |
| 26 | int c = dungeon[0].size(); // column size |
| 27 | vector<vector<int>> dp(r, vector<int>(c)); // initializing the DP table with same size as given matrix |
| 28 | // looping for filling the DP array starting from bottom right cell. the pattern is right to left ,then down to top |
| 29 | for (int i = r - 1; i >= 0; --i) |
| 30 | { |
| 31 | for (int j = c - 1; j >= 0; --j) |
| 32 | { |
| 33 | if (i == r - 1 && j == c - 1) //Bottom-Right cell (Princess Cell) (point 1.) |
| 34 | dp[i][j] = min(0, dungeon[i][j]); // taking min so as to replace the positive value with 0 |
| 35 | else if (i == r - 1) //last row, (point 2) |
| 36 | dp[i][j] = min(0, dungeon[i][j] + dp[i][j + 1]); // taking min so as to replace the positive value with 0 |
| 37 | else if (j == c - 1) //last col, point (3) |
| 38 | dp[i][j] = min(0, dungeon[i][j] + dp[i + 1][j]); // taking min so as to replace the positive value with 0 |
| 39 | else // any other cell (point 4) |
| 40 | dp[i][j] = min(0, dungeon[i][j] + max(dp[i][j + 1], dp[i + 1][j])); // taking min so as to replace the positive value with 0 |
| 41 | } |
| 42 | } |
| 43 | return abs(dp[0][0]) + 1; // Adding one because the knight can not start with value 0 as mentioned in point 5 |
| 44 | } |
| 45 | }; |
nothing calls this directly
no outgoing calls
no test coverage detected