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.
Like before the bean-eater, but added some restrictions, is in the upper left to the lower right corner of the path can not let the Knight's blood volume is less than 0, so we are looking for is not to go to the end of the last remaining blood volume of the path, but the path of the smallest value of the most. Because there are positive numbers in the path, it is more troublesome to handle it, so consider reverse processing, from the lower-right corner to the upper-left corner, Dp[i][j] to indicate the amount of blood required from coordinates (I, j) to the lower right corner. When initialized, assume that the last remaining blood is 0, and
State transition equation:
DUNGEON[I][J] = max (min (dungeon[i][j+1], dungeon[i+1][j])-dungeon[i][j], 0)
1 classSolution {2 Public:3 intCALCULATEMINIMUMHP (vector<vector<int> > &Dungeon) {4 intm =dungeon.size ();5 intn = dungeon[0].size ();6dungeon[m-1][n-1] = max (0-dungeon[m-1][n-1],0);7 for(inti = m-2; I >=0; --i) {8dungeon[i][n-1] = max (dungeon[i+1][n-1]-dungeon[i][n-1],0);9 }Ten for(intj = N-2; J >=0; --j) { Onedungeon[m-1][J] = max (dungeon[m-1][j+1]-dungeon[m-1][J],0); A } - for(inti = m-2; I >=0; --i) { - for(intj = N-2; J >=0; --j) { theDUNGEON[I][J] = max (min (dungeon[i][j+1], dungeon[i+1][J])-dungeon[i][j],0); - } - } - returndungeon[0][0] +1; + } -};
[Leetcode] Dungeon Game