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) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).
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 is able to rescue the princess.
For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN
.
Notes:
分析:
動態規劃的題,時間復雜度和空間復雜度都是O(m*n),其中空間復雜度可以利用滾動數組優化為O(min(m,n));
class Solution { public: int calculateMinimumHP(vector>& dungeon) { if(dungeon.empty() || dungeon[0].empty()) return -1; int rows=dungeon.size(),cols=dungeon[0].size(); vector > dp(rows,vector (cols,0)); dp.back().back()=dungeon.back().back()>=0?1:1+(-1)*dungeon.back().back(); int begini=rows-1,beginj=cols-2; if(cols==1) { if(rows==1) return dp[0][0]; else { begini=rows-2; beginj=0; } } for(int i=begini;i>=0;--i) { for(int j=i==begini?beginj:cols-1;j>=0;--j) { int tmp; if(i