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.
The prince rescued the princess is quite novel, my first idea is to compare the right and bottom of the number of the size, to the big one, but this algorithm for some cases, such as the following situation:
1 (K) |
-3 |
3 |
0 |
-2 |
0 |
-3 |
-3 |
-3 (P)
|
If the path to my algorithm is 1---0--2--0--3, so that the knight's initial blood volume is 5, and the correct path should be 1, 3, 3, 0--3 so the Knight's Knight Blood volume Just for 3. Helpless had to go online to see the solution of the great God, found that unification is to do with dynamic planning programming, build a two-dimensional array with the same size as the maze to indicate the starting blood volume of the current position, the first initialization is the Princess room starting life, and then slowly spread to the first room , the optimal starting health of each position is constantly obtained. The recursive equation is: The recursive equation is dp[i][j] = max (1, Min (Dp[i+1][j], dp[i][j+1])-dungeon[i][j]). The code is as follows:
classSolution { Public: intCALCULATEMINIMUMHP (vector<vector<int> > &Dungeon) { intm =dungeon.size (); intn = dungeon[0].size (); intDp[m][n]; Dp[m-1][n-1] = max (1,1-Dungeon[m-1][n-1]); for(inti = m-2; I >=0; --i) {dp[i][n-1] = max (1, Dp[i +1][n-1]-Dungeon[i][n-1]); } for(intj = N-2; J >=0; --j) {Dp[m-1][J] = max (1, Dp[m-1][j +1]-Dungeon[m-1][j]); } for(inti = m-2; I >=0; --i) { for(intj = N-2; J >=0; --j) {Dp[i][j]= Max (1, min (dp[i +1][J], Dp[i][j +1]) -Dungeon[i][j]); } } returndp[0][0]; }};
[Leetcode] Dungeon Game Dungeon Games