The demons had captured the princess § 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.
DP:
从后往前走,最后一个屋子的答案是6 然后上面是5 左面是1 。。。。。。
class Solution {
public int calculateMinimumHP(int[][] dungeon) {
int n = dungeon.length;
int m = dungeon[0].length;
int[][] result = new int[n][m];
for (int i = n - 1; i >= 0; i--) {
for (int j = m - 1; j >= 0; j--) {
if (i == n - 1 && j == m - 1) {
result[i][j] = dungeon[i][j] >= 0 ? 1 : 1 - dungeon[i][j];
} else if (i == n - 1) {
result[i][j] = dungeon[i][j] >= result[i][j + 1]
? 1 : result[i][j + 1] - dungeon[i][j];
} else if (j == m - 1) {
result[i][j] = dungeon[i][j] >= result[i + 1][j]
? 1 : result[i + 1][j] - dungeon[i][j];
} else {
int min = Math.min(result[i][j + 1], result[i + 1][j]);
result[i][j] = dungeon[i][j] >= min ? 1 : min - dungeon[i][j];
}
}
}
return result[0][0];
}
}
优化 : 可以使用一维数组代替二维数组
将result中的 i 的索引都删掉即可。
class Solution {
public int calculateMinimumHP(int[][] dungeon) {
int n = dungeon.length;
int m = dungeon[0].length;
int[] result = new int[m];
for (int i = n - 1; i >= 0; i--) {
for (int j = m - 1; j >= 0; j--) {
if (i == n - 1 && j == m - 1) {
result[j] = dungeon[i][j] >= 0 ? 1 : 1 - dungeon[i][j];
} else if (i == n - 1) {
result[j] = dungeon[i][j] >= result[j + 1]
? 1 : result[j + 1] - dungeon[i][j];
} else if (j == m - 1) {
result[j] = dungeon[i][j] >= result[j]
? 1 : result[j] - dungeon[i][j];
} else {
int min = Math.min(result[j + 1], result[j]);
result[j] = dungeon[i][j] >= min ? 1 : min - dungeon[i][j];
}
}
}
return result[0];
}
}