[leetcode] 174. Dungeon Game 解题报告

题目链接:https://leetcode.com/problems/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.

思路:在走完最后一个房间的时候血量至少要剩下1,因此最后的状态可以当成是初始状态,由后往前依次决定在每一个位置至少要有多少血量, 这样一个位置的状态是由其下面一个和和左边一个的较小状态决定 .因此一个基本的状态方程是: dp[i][j] = min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j]. 

但是还有一个条件就是在每一个状态必须血量都要大于1,因此我们还需要一个方程在保证在每一个状态都大于1,即:dp[i][j] = max(dp[i][j], 1); 也就是说虽然当前的血量到最后能够剩下1,但是现在已经低于1了,我们需要为其提升血量维持每一个状态至少都为1.

这样我们需要一个二维数组在记录我们需要的之前的状态,也就是一个位置的下方和左方的状态.而其下方的状态可以存储在其当前位置,因此我们可以做状态压缩,只需要一维的数组.

代码如下:

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

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

参考:https://leetcode.com/discuss/62763/a-12-ms-c-solution-dp








评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值