题目:
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) 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:
分析:
动态规划的题,时间复杂度和空间复杂度都是O(m*n),其中空间复杂度可以利用滚动数组优化为O(min(m,n));
class Solution { public: int calculateMinimumHP(vector<vector<int>>& dungeon) { if(dungeon.empty() || dungeon[0].empty()) return -1; int rows=dungeon.size(),cols=dungeon[0].size(); vector<vector<int>> dp(rows,vector<int>(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<rows-1 && j<cols-1) { tmp=min(dp[i+1][j],dp[i][j+1])-dungeon[i][j]; } else if(i<rows-1) { tmp=dp[i+1][j]-dungeon[i][j]; } else { tmp=dp[i][j+1]-dungeon[i][j]; } dp[i][j]=max(1,tmp); } } return dp[0][0]; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/bupt8846/article/details/47093793