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
.
-2 (K) | -3 | 3 |
-5 | -10 | 1 |
10 | 30 | -5 (P) |
Notes:
- The knight's health has no upper bound.
- Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
思路: 仔细看了题目以后,觉得可以用DP来做。不知为什么被归为binary search类别中的。
所以方法1.DP , 大家都懂的。这里有个点,如果原来的矩阵可以更改的话,空间复杂度就是O(1),如果不更改的话,就是空间复杂度可以简化为O(n),时间复杂度还是O(m*n)
class Solution { public: int calculateMinimumHP(vector<vector<int> > &dungeon) { if(dungeon.empty()) return 0; int row = dungeon.size(); int col = dungeon[0].size(); vector<int> health(col,1); for(int i=row-1;i>=0;i--){ for(int j=col-1;j>=0;j--){ if(i==row-1 && j==col-1){ health[j] = max(1,1-dungeon[i][j]); }else if(i==row-1){ health[j] = max(1,health[j+1]-dungeon[i][j]); }else if(j==col-1){ health[j] = max(1,health[j]-dungeon[i][j]); }else{ health[j] = min(health[j]-dungeon[i][j],health[j+1]-dungeon[i][j]); if(health[j]<0) health[j]=1; } } } return health[0]; } };