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.
Public classSolution { Public intCALCULATEMINIMUMHP (int[] Dungeon) { /*DP thought, and it was from the right down to the top left, and walked backwards. The meaning of dp[i][j] is the minimum health required to i,j points, note that the last row and the last column are taken into account when traversing the midpoint, note that the final result needs to be added 1!! from the bottom right to the left. */ if(dungeon==NULL|| dungeon.length<=0| | dungeon[0].length<=0)return-1; introw=dungeon.length; intCol=dungeon[0].length; int[] dp=New int[Row][col]; Dp[row-1][col-1]=math.max (0-dungeon[row-1][col-1],0); for(inti=row-2;i>=0;i--) {Dp[i][col-1]=math.max (dp[i+1][col-1]-dungeon[i][col-1],0); } for(inti=col-2;i>=0;i--) {Dp[row-1][i]=math.max (dp[row-1][i+1]-dungeon[row-1][i],0); } for(inti=row-2;i>=0;i--){ for(intj=col-2;j>=0;j--) {Dp[i][j]=math.max (Math.min (dp[i+1][j],dp[i][j+1])-dungeon[i][j],0); } } returnDp[0][0]+1; }}
[Leedcode 174] Dungeon Game