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.
跟之前的吃豆人一题很像,但是加了一些限制,就是在从左上角到右下角的路径中不能让骑士的血量低于0,所以我们要找的不是走到最后剩余血量最多的那一条路径,而是路径上的最小值最大的那一条。因为路径中还有正数,所以正向处理起来感觉比较麻烦,可以考虑逆向处理,从右下角像左上角处理,dp[i][j]表示从坐标(i, j)到右下角所需的血量。初始化时假设最后剩余血里为0,而
状态转移方程:
dungeon[i][j] = max(min(dungeon[i][j+1], dungeon[i+1][j])-dungeon[i][j], 0)
1 class Solution { 2 public: 3 int calculateMinimumHP(vector<vector<int> > &dungeon) { 4 int m = dungeon.size(); 5 int n = dungeon[0].size(); 6 dungeon[m-1][n-1] = max(0-dungeon[m-1][n-1], 0); 7 for (int i = m - 2; i >= 0; --i) { 8 dungeon[i][n-1] = max(dungeon[i+1][n-1]-dungeon[i][n-1], 0); 9 } 10 for (int j = n - 2; j >= 0; --j) { 11 dungeon[m-1][j] = max(dungeon[m-1][j+1]-dungeon[m-1][j], 0); 12 } 13 for (int i = m - 2; i >= 0; --i) { 14 for (int j = n - 2; j >= 0; --j) { 15 dungeon[i][j] = max(min(dungeon[i][j+1], dungeon[i+1][j])-dungeon[i][j], 0); 16 } 17 } 18 return dungeon[0][0] + 1; 19 } 20 };