Dungeon Game
The Demons had captured the Princess (P) and imprisoned her in the Bottom-right corner of a dungeon. The dungeon consists of M x N Rooms laid out in a 2D grid. Our Valiant Knight (K) is initially positioned in the top-left, and must fight his, through the dungeon to rescue The princess.
The knight has an initial health point represented by a positive integer. Drops to 0 or below, he dies immediately.
Some of the rooms is guarded by demons, so the knight loses health (negative integers) upon entering these rooms ; Other rooms is either empty (0 ' s) or contain magic orbs that increase the knight ' s Health (positive int Egers).
In order to reach the princess as quickly as possible, the Knight decides to move only rightward or downward in each step.
Write a function to determine the knight's minimum initial health so that he's able to rescue the princess.
For example, given the dungeon below, the initial health of the knight must is at least 7 if he follows the optimal path c0/>.
-2 (K) |
-3 |
3 |
-5 |
-10 |
1 |
10 |
30 |
-5 (P) |
Notes:
- The Knight ' s Health has no upper bound.
- Any hostel can contain threats or power-ups, even the first, the knight enters and the Bottom-right, where the Princ ESS is imprisoned.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
classSolution { Public: intCALCULATEMINIMUMHP (vector<vector<int> > &Dungeon) { intm =dungeon.size (); intn = dungeon[0].size (); Vector<vector<int> > Ret (M, vector<int>(n)); Ret[m-1][n-1] = max (1,1-dungeon[m-1][n-1]); for(inti = m2; I >=0; I--) Ret[i][n-1] = max (1, ret[i+1][n-1]-dungeon[i][n-1]); for(intj = N2; J >=0; J--) Ret[m-1][J] = max (1, ret[m-1][j+1]-dungeon[m-1][j]); for(inti = m2; I >=0; I--) { for(intj = N2; J >=0; J--) {Ret[i][j]= Max (1, Min (ret[i+1][J]-DUNGEON[I][J], ret[i][j+1]-dungeon[i][j])); } } returnret[0][0]; }};
"Leetcode" Dungeon Game