|
| 1 | +/* |
| 2 | +
|
| 3 | +Problem Link : https://leetcode.com/problems/dungeon-game/ |
| 4 | +
|
| 5 | +asking questions |
| 6 | +
|
| 7 | +At any point if our health gets zero of below we dies, athem so : we need 1 + (-mat[i][j]) for our health to be one. |
| 8 | +
|
| 9 | +What if we get some health if we arrive at some cell ? my guess is we still need 1 health in first case to arrive at that cell - cases like these need to be figure out by yourself. |
| 10 | +
|
| 11 | +at any cell what health do we need ? - since we can go only down and right therefore min health required will be minimun health required if we go right or down, |
| 12 | +( futher explained in arriving at recurrance relation heading ) |
| 13 | +
|
| 14 | +for brief answers/explanation for above point 1 and 2 , assume a 1D matrix this is what is ment by 1st and 2nd point. |
| 15 | +
|
| 16 | +[[-10]] : ans = 1 + (-(-10)) = 11 (explanation to first point mentioned) |
| 17 | +[[10]] : ans = 1 as we still need 1 health at first place to get there (explanation to second point mentioned) |
| 18 | +[[-2,-3,3,-5,-10]] : ans = 1 + (-(-17)) = 18 same as 1st case |
| 19 | +[[2,3,3,5,10]] : ans = 1 same as 2nd test case, explanation to second point mentioned to asking question |
| 20 | +
|
| 21 | +*/ |
| 22 | + |
| 23 | + |
| 24 | + |
| 25 | + |
| 26 | +class Solution { |
| 27 | +public: |
| 28 | + int dp[205][205]; |
| 29 | + int find(int i,int j,vector<vector<int>>& v){ |
| 30 | + int n=v.size(),m=v[0].size(); |
| 31 | + if(i==n || j==m)return 1e9+5; // Base Case |
| 32 | + if(i==n-1 && j==m-1){ |
| 33 | + return v[i][j]<=0?1-v[i][j]:1; // when we reach the bottom-right |
| 34 | + } |
| 35 | + if(dp[i][j]!=1e9+5)return dp[i][j]; |
| 36 | + int required = min(find(i,j+1,v),find(i+1,j,v))-v[i][j]; // taking the minimum requirement from down and right room |
| 37 | + |
| 38 | + return dp[i][j]=required<=0?1:required; |
| 39 | + } |
| 40 | + |
| 41 | + int calculateMinimumHP(vector<vector<int>>& dungeon) { |
| 42 | + for(int i=0;i<=203;i++){ |
| 43 | + for(int j=0;j<=203;j++)dp[i][j]=1e9+5; |
| 44 | + } |
| 45 | + return find(0,0,dungeon); |
| 46 | + } |
| 47 | +}; |
0 commit comments