[LeetCode] 174. Dungeon Game 地牢游戏

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.

Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

妖怪抓到了公主,把她关在了地牢的右下角,地牢是由M x N 的房子组成的2D方格。勇敢的骑士从左上角开始出发取救公主,有的房间是负数表示里面是妖怪,会减血量。有的房间是0,没东西,血量不变。有的是整数表示魔法瓶,会增加血量。为了尽快救出公主,骑士只能向下和向右走,写一个函数计算骑士最少的起始血量。

这个问题和"Maximum/Minimum Path Sum"很相似。然而,具有全局最大HP(生命值)收益的路径并不一定可以保证最小的初始HP,因为题目中具有限制条件:HP不能≤0。例如,考虑下面的两条路径:0 -> -300 -> 310 -> 0 和 0 -> -1 -> 2 -> 0。这两条路径的净HP收益分别是-300 + 310 = 10 与 -1 + 2 = 1。第一条路径的净收益更高,但是它所需的初始HP至少是301,才能抵消第二个房间的-300HP损失,而第二条路径只需要初始HP为2就可以了。

解法:动态归化DP,建立一个和迷宫大小相同的二维数组用来表示当前位置出发的起始血量,从结尾开始,最先初始化的是公主所在的房间的起始生命值,然后慢慢向第一个房间扩散,不断的得到各个位置的最优的起始生命值。

State: dp[i][j],表示当前位置到结尾最少需要的血量。

Function: dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j]), 因为骑士的血量不能≤0,所以用max函数保证最少是1。

Initialize: dp[M-1][N-1] = grid[M-1][N-1]

Return: dp[0][0]

Java:

public class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        if (dungeon.length == 1 && dungeon[0].length == 1){
            if (dungeon[0][0] > 0){
                return 1;
            } else {
                return -dungeon[0][0] + 1;
            }
        }
        int len = dungeon[0].length;
        int row = dungeon.length;
        int[] min = new int[len];
        min[len - 1] = -dungeon[row - 1][len - 1] + 1;
        min[len - 1] = Math.max(min[len - 1], 1);
        for (int i = len - 2; i >= 0; i--){
            min[i] = min[i + 1] - dungeon[row - 1][i];
            min[i] = Math.max(min[i], 1);
        }
        for (int i = row - 2; i >= 0; i--){
            min[len - 1] = min[len - 1] - dungeon[i][len - 1];
            min[len - 1] = Math.max(min[len - 1], 1);
            for (int j = len - 2; j >= 0; j--){
                min[j] = Math.min(min[j + 1], min[j]) - dungeon[i][j];
                min[j] = Math.max(min[j], 1);
            }
        }
        return min[0];
    }
}

Python:

class Solution:
    # @param dungeon, a list of lists of integers
    # @return a integer
    def calculateMinimumHP(self, dungeon):
        DP = [float("inf") for _ in dungeon[0]]
        DP[-1] = 1
        
        for i in reversed(xrange(len(dungeon))):
            DP[-1] = max(DP[-1] - dungeon[i][-1], 1)
            for j in reversed(xrange(len(dungeon[i]) - 1)):
                min_HP_on_exit = min(DP[j], DP[j + 1])
                DP[j] = max(min_HP_on_exit - dungeon[i][j], 1)
                
        return DP[0]  

C++:

class Solution {
public:
    int calculateMinimumHP(vector<vector<int> > &dungeon) {
        int m = dungeon.size();
        int n = dungeon[0].size();
        int dp[m][n];
        dp[m - 1][n - 1] = max(1, 1 - dungeon[m - 1][n - 1]);
        for (int i = m - 2; i >= 0; --i) {
            dp[i][n - 1] = max(1, dp[i + 1][n - 1] - dungeon[i][n - 1]);
        }
        for (int j = n - 2; j >= 0; --j) {
            dp[m - 1][j] = max(1, dp[m - 1][j + 1] - dungeon[m - 1][j]);
        }
        for (int i = m - 2; i >= 0; --i) {
            for (int j = n - 2; j >= 0; --j) {
                dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
            }
        }
        return dp[0][0];
    }
};

 

类似题目:

[LeetCode] 64. Minimum Path Sum 最小路径和

 

All LeetCode Questions List 题目汇总

 

posted @ 2018-02-26 05:39  轻风舞动  阅读(467)  评论(0编辑  收藏  举报