【LeetCode】174. Dungeon Game 地下城游戏(Hard)(JAVA)
题目地址: https://leetcode.com/problems/dungeon-game/
题目描述:
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.
-2 (K) | -3 | 3 |
-5 | -10 | 1 |
10 | 30 | -5 (P) |
Note:
- 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.
题目大意
一些恶魔抓住了公主(P)并将她关在了地下城的右下角。地下城是由 M x N 个房间组成的二维网格。我们英勇的骑士(K)最初被安置在左上角的房间里,他必须穿过地下城并通过对抗恶魔来拯救公主。
骑士的初始健康点数为一个正整数。如果他的健康点数在某一时刻降至 0 或以下,他会立即死亡。
有些房间由恶魔守卫,因此骑士在进入这些房间时会失去健康点数(若房间里的值为负整数,则表示骑士将损失健康点数);其他房间要么是空的(房间里的值为 0),要么包含增加骑士健康点数的魔法球(若房间里的值为正整数,则表示骑士将增加健康点数)。
为了尽快到达公主,骑士决定每次只向右或向下移动一步。
编写一个函数来计算确保骑士能够拯救到公主所需的最低初始健康点数。
解题方法
- 采用动态规划,找出动态规划函数(从最左走到最右的基本都是用动态规划)
- 从最右下角开始,看王子当前需要的血量(至少要大于 0 才能活,首先和 0 比较,最后再加上 1 即可)
- 如果 dp[i][j] 后面的元素都已经知道结果了,如何算 dp[i][j] 呢?
- 先比较下 dp[i][j + 1] 和 dp[i + 1][j] 哪个需要血量少,就取哪个: Math.min(dp[i + 1][j], dp[i][j + 1])
- 当前的 dungeon[i][j] 需要的血量: -dungeon[i][j] (因为负数是扣血也就是需要的血量要取反)
- -dungeon[i][j] + Math.min(dp[i + 1][j], dp[i][j + 1]) 两个加起来如果是负数,明显就是不需要血量,结果就是 0 ,所以和 0 取最大值
- 再考虑边界就可以了
class Solution {
public int calculateMinimumHP(int[][] dungeon) {
if (dungeon.length == 0 || dungeon[0].length == 0) return 0;
int[][] dp = new int[dungeon.length][dungeon[0].length];
for (int i = dungeon.length - 1; i >= 0; i--){
for (int j = dungeon[0].length - 1;j >= 0; j--) {
if (i == dungeon.length - 1 && j == dungeon[0].length - 1) {
dp[i][j] = Math.max(0, -dungeon[i][j]);
} else if (i == dungeon.length - 1) {
dp[i][j] = Math.max(0, -dungeon[i][j] + dp[i][j + 1]);
} else if (j == dungeon[0].length - 1) {
dp[i][j] = Math.max(0, -dungeon[i][j] + dp[i + 1][j]);
} else {
dp[i][j] = Math.max(0, -dungeon[i][j] + Math.min(dp[i + 1][j], dp[i][j + 1]));
}
}
}
return dp[0][0] + 1;
}
}
执行耗时:2 ms,击败了90.23% 的Java用户
内存消耗:38.3 MB,击败了70.14% 的Java用户