Dungeon Game
2015.1.23 19:38
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
Ten 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.
Solution:
This problem should is one about dynamic programming. Let Dp[i][j] is the minimal HP necessary to reach the destination (n-1, m-1), if-you-start from the position (I, J). Then the answer lies in dp[0][0], which'll be is calculated backward from (n-1, m-1) all the the-the-the-the-same-to (0, 0).
Try to understand the meaning of min (), even if you can pass a position (I, j), and you'll always be need at least 1 point of HP To stay alive.
Time and space complexity is both O (n * m), though space can is reduced to O (m) with extra coding, what do you know?
Accepted Code:
1 classSolution {2 Public:3 intCALCULATEMINIMUMHP (vector<vector<int> > &Dungeon) {4 intN, M;5 6n = (int) dungeon.size ();7m = (int) dungeon[0].size ();8 9 intI, J;Tenvector<vector<int> >DP; One ADp.resize (N, vector<int>(m)); -Dp[n-1][m-1] = min (1-Dungeon[n-1][m-1]); - for(i = n-2; I >=0; --i) { theDp[i][m-1] = min (dp[i +1][m-1]-Dungeon[i][m-1]); - } - for(j = m-2; J >=0; --j) { -Dp[n-1][j] = min (Dp[n-1][j +1]-Dungeon[n-1][j]); + } - + ints1, S2; A for(i = n-2; I >=0; --i) { at for(j = m-2; J >=0; --j) { -S1 = dp[i][j +1]; -S2 = dp[i +1][j]; -Dp[i][j] = min (S1 < s2? s1:s2)-dungeon[i][j]); - } - } inS1 = dp[0][0]; - for(i =0; I < n; ++i) { to dp[i].clear (); + } - dp.clear (); the * returnS1; $ }Panax Notoginseng Private: - intMinintx) { the returnX <=0?1: x; + } A};
Leetcode-dungeon Game