您的位置:首页 > 其它

Dungeon Game 解答

2015-10-18 13:18 357 查看

Question

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)-33
-5-101
1030-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.

Solution

这道题一看就知道用DP做。但是如果是从(0,0)开始推到(m - 1, n - 1),对于每个点,我们需要纪录两个值: 1. 走到该点需要的最少血量 2. 该点富余的血量。这样,我们无法得到一个判断标准。

所以,我们从反方向出发。从(m - 1, n - 1)到(0,0),hp[i][j] 代表从(i,j)走到终点需要的最少血量。如果dungeon[i][j]的值为负,那么进入这个格子之前knight需要有的最小HP是-dungeon[i][j] + min(left, right).如果格子的值非负,那么最小HP需求就是1。

public class Solution {
public int calculateMinimumHP(int[][] dungeon) {
int m = dungeon.length, n = dungeon[0].length;
int[][] hp = new int[m]
;
hp[m - 1][n - 1] = Math.max(-dungeon[m - 1][n - 1] + 1, 1);
for (int i = m - 2; i >= 0; i--) {
hp[i][n - 1] = Math.max(-dungeon[i][n - 1] + hp[i + 1][n - 1], 1);
}
for (int i = n - 2; i >= 0; i--) {
hp[m - 1][i] = Math.max(-dungeon[m - 1][i] + hp[m - 1][i + 1], 1);
}

for (int i = m - 2; i >= 0; i--) {
for (int j = n - 2; j >= 0; j--) {
hp[i][j] = Math.max(1, -dungeon[i][j] + Math.min(hp[i + 1][j], hp[i][j + 1]));
}
}
return hp[0][0];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: