Dungeon Game in C++

C++Server Side ProgrammingProgramming

Suppose there is a story like the demons had captured the princess whose name is P and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M row, N column grid-like rooms. Our valiant knight named K was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.

Now the knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies at that moment.

Some of the rooms have demons to guard that room, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty or contain magic orbs that increase the knight's health (positive integers).

So if he wants to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. We have to find the minimal initial health that will be sufficient to reach P. So if the input is like, then the answer will be 6, as K can reach to P, using the path Right -> Right -> Down -> Down

-2(k)-23
-5-101
1030-5p

To solve this, we will follow these steps −

  • r := row of dp, c := col of dp

  • for initializing j := r - 2, when j >= 0, decrease j by 1 do −

    • dp[j, c - 1] := minimum of dp[j, c - 1] and dp[j, c - 1] + dp[j + 1, c - 1]

  • for initializing j := c - 2, when j >= 0, decrease j by 1 do −

    • dp[r - 1, j] := minimum of dp[r - 1, j] and dp[r – 1, j] + dp[r – 1, j + 1]

  • for initializing i := r - 2, when i >= 0, decrease i by 1 do −

    • for initializing j := c - 2, when j >= 0, decrease j by 1 do −

      • dp[i, j] := minimum of dp[i, j] and maximum of dp[i, j] + dp[i + 1, j] and dp[i, j] + dp[i, j + 1]

  • if dp[0, 0] <= 0, then,

    • return |dp[0, 0]| + 1

  • return 1

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
lli min(lli a, lli b){
   return a <= b ? a : b;
}
lli max(lli a, lli b){
   return a <= b ? b : a;
}
class Solution {
public:
   int calculateMinimumHP(vector<vector<int>>& dp) {
      int r = dp.size();
      int c = dp[0].size();
      for(lli j=r-2;j>=0;j--){
         dp[j][c-1] = min(dp[j][c-1], dp[j][c-1]+dp[j+1][c-1]);
      }
      for(lli j = c-2;j>=0;j--){
         dp[r-1][j] =min(dp[r-1][j], dp[r-1][j]+dp[r-1][j+1]);
      }
      for(lli i = r-2;i>=0;i--){
         for(lli j = c-2;j>=0;j--){
            dp[i][j] = min(dp[i][j],max(dp[i][j]+dp[i+1][j],dp[i][j]+dp[i][j+1]));
         }
      }
      if(dp[0][0] <= 0 )return abs(dp[0][0])+1;
      return 1;
   }
};
main(){
   Solution ob;
   vector<vector<int>> v = {{-2,-2,3},{-5,-10,1},{10,30,-5}};
   cout << (ob.calculateMinimumHP(v));
}

Input

{{-2,-2,3},{-5,-10,1},{10,30,-5}}

Output

6
raja
Published on 26-May-2020 17:22:08
Advertisements