Dungeon GameThe 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 (

negativeintegers) upon entering these rooms; other rooms are either empty (0’s) or contain magic orbs that increase the knight’s health (positiveintegers).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

7if 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.

Credits:

Special thanks to @stellari for adding this problem and creating all test cases.

Dynamic programming.

But we should start at the end point, inversely traverse the dynamic 2D array.

if the life at some point is negative, set it to 1.

The life before knight go the the end point should be bigger than or equal to -dungeon[height – 1][width – 1] + 1.

//What if the knight does not need life when finished? Set it to 1 //At any step, the knight's life should not be smaller than 1 class Solution { public: int calculateMinimumHP(vector<vector<int>>& dungeon) { int height = dungeon.size(); int width = dungeon[0].size(); long dp[height][width]; dp[height - 1][width - 1] = -dungeon[height - 1][width - 1] + 1;//BUG here if(dp[height - 1][width - 1] < 1) dp[height - 1][width - 1] = 1; for(int i = height - 2; i >= 0; i--){ dp[i][width - 1] = dp[i + 1][width - 1] - dungeon[i][width - 1]; if(dp[i][width - 1] < 1) dp[i][width - 1] = 1; } for(int j = width - 2; j >= 0; j--){ dp[height - 1][j] = dp[height - 1][j + 1] - dungeon[height - 1][j]; if(dp[height - 1][j] < 1) dp[height - 1][j] = 1; } for(int i = height - 2; i >= 0; i--){//bug here, use int not size_t for(int j = width - 2; j >= 0; j--){ dp[i][j] = min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]; if(dp[i][j] < 1) dp[i][j] = 1; } } return dp[0][0]; } };