https://leetcode.com/problems/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 right->right->down->down.
-2 (K) |
-3 |
3 |
-5 |
-10 |
1 |
10 |
30 |
-5 (P) |
Notes:
1.The Knight ' s Health has no upper bound.
2. Any can contain threats or power-ups, even the first, the knight enters and the Bottom-right, where the PR Incess is imprisoned.
classSolution { Public: intCALCULATEMINIMUMHP (vector<vector<int>>&Dungeon) { if(dungeon.size () = =0)return 1; intm = Dungeon.size (), n = dungeon[0].size (); Vector<vector<int> > DP (M, vector<int> (n,0)); Dp[m-1][n-1] = (1-dungeon[m-1][n-1]<=0)?1:1-dungeon[m-1][n-1]; for(intj=n-2; j>=0;--j) {Dp[m-1][J] = (dp[m-1][j+1]-dungeon[m-1][J] <=0)?1: dp[m-1][j+1]-dungeon[m-1][j]; } for(inti=m-2; i>=0;--i) {dp[i][n-1] = (dp[i+1][n-1]-dungeon[i][n-1] <=0)?1: dp[i+1][n-1]-dungeon[i][n-1]; } for(intj=n-2; i>=0;--i) { for(intj=n-2; j>=0;--j) {BOOLFlag = (dp[i][j+1]<=DUNGEON[I][J] | | dp[i+1][j]<=Dungeon[i][j]); DP[I][J]= Flag?1: Min (dp[i][j+1]-DUNGEON[I][J], dp[i+1][j]-Dungeon[i][j]); } } returndp[0][0]; }};
View Code
[email protected] [174] Dungeon Game (Dynamic programming)