一些恶魔抓住了公主(P)并将她关在了地下城的右下角。地下城是由 M x N 个房间组成的二维网格。我们英勇的骑士(K)最初被安置在左上角的房间里,他必须穿过地下城并通过对抗恶魔来拯救公主。
骑士的初始健康点数为一个正整数。如果他的健康点数在某一时刻降至 0 或以下,他会立即死亡。
有些房间由恶魔守卫,因此骑士在进入这些房间时会失去健康点数(若房间里的值为负整数,则表示骑士将损失健康点数);其他房间要么是空的(房间里的值为 0),要么包含增加骑士健康点数的魔法球(若房间里的值为正整数,则表示骑士将增加健康点数)。
为了尽快到达公主,骑士决定每次只向右或向下移动一步。
编写一个函数来计算确保骑士能够拯救到公主所需的最低初始健康点数。
例如,考虑到如下布局的地下城,如果骑士遵循最佳路径 右 -> 右 -> 下 -> 下,则骑士的初始健康点数至少为 7。
DFS
深度优先搜索,遍历所有路线。会有很多重复计算。
class Solution {
public int calculateMinimumHP(int[][] dungeon) {
return dfs(dungeon, 0, 0, dungeon.length, dungeon[0].length);
}
private int dfs(int[][] dungeon, int i, int j, int rows, int cols) {
if (i == rows - 1 && j == cols - 1)
return Math.max(1 - dungeon[i][j], 1);
if (i == rows - 1)
return Math.max(dfs(dungeon, i, j + 1, rows, cols) - dungeon[i][j], 1);
if (j == cols - 1)
return Math.max(dfs(dungeon, i + 1, j, rows, cols) - dungeon[i][j], 1);
return Math.max(Math.min(dfs(dungeon, i + 1, j, rows, cols), dfs(dungeon, i, j + 1, rows, cols)) - dungeon[i][j], 1);
}
}
DFS+记忆化
构造一个 memory 数组,用来存放已经计算过的结果。
class Solution {
private int[][] memory;
public int calculateMinimumHP(int[][] dungeon) {
int rows = dungeon.length, cols = dungeon[0].length;
memory = new int[rows][cols];
return dfs(dungeon, 0, 0, rows, cols);
}
private int dfs(int[][] dungeon, int i, int j, int rows, int cols) {
if (i == rows - 1 && j == cols - 1)
return Math.max(1 - dungeon[i][j], 1);
if (memory[i][j] > 0)
return memory[i][j];
int min = 0;
if (i == rows - 1)
min = Math.max(dfs(dungeon, i, j + 1, rows, cols) - dungeon[i][j], 1);
else if (j == cols - 1)
min = Math.max(dfs(dungeon, i + 1, j, rows, cols) - dungeon[i][j], 1);
else
min = Math.max(Math.min(dfs(dungeon, i + 1, j, rows, cols), dfs(dungeon, i, j + 1, rows, cols)) - dungeon[i][j], 1);
memory[i][j] = min;
return min;
}
}
动态规划
class Solution {
public int calculateMinimumHP(int[][] dungeon) {
int rows = dungeon.length, cols = dungeon[0].length;
int[][] dp = new int[rows + 1][cols + 1];
for (int i = 0; i <= cols; ++i)
dp[rows][i] = Integer.MAX_VALUE;
for (int i = 0; i <= rows; ++i)
dp[i][cols] = Integer.MAX_VALUE;
dp[rows][cols - 1] = dp[rows - 1][cols] = 1;
for (int i = rows - 1; i >= 0; --i) {
for (int j = cols - 1; j >= 0; --j) {
int min = Math.min(dp[i][j + 1], dp[i + 1][j]);
dp[i][j] = Math.max(min - dungeon[i][j], 1);
}
}
return dp[0][0];
}
}