跳转至

174.Dungeon Game

Tags: Hard Dynamic Programming

Links: 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)

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.

这道题就是首先要注意,在每个位置的健康值必须大于0,所以在每个位置的健康值最小的数值为1,构建一个数组,其中d[i][j]表示在于i - 1, j - 1的时候,扣除掉伤害值后的健康值,比如说,在终点为1。然后从终点开始往起点进行转移,那么最右边的一列,最下边的一行,转移方向都只有一个,直接预先计算出结果。这样最后得到的d[1][1]就是还没有扣除位于dungeon[0][0]的伤害值后的结果。

注意,时时需要保证在每个位置的结果大于0,时间复杂度O(mn)

class Solution {
public:
    int calculateMinimumHP(vector<vector<int>>& dungeon) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        int  m= dungeon.size(), n = dungeon[0].size();
        vector<vector<int>> d(m + 1, vector<int>(n + 1));
        d[m][n] = 1;
        for (int i = m - 1; i >= 1; --i) 
            d[i][n] = (d[i + 1][n] - dungeon[i][n - 1]) > 0 ? (d[i + 1][n] - dungeon[i][n - 1]) : 1;


        for (int i = n - 1; i >= 1; --i) 
            d[m][i] = (d[m][i + 1] - dungeon[m - 1][i]) > 0 ? (d[m][i + 1] - dungeon[m - 1][i]) : 1;

        for (int i = m - 1; i >= 1; --i) {
            for (int j = n - 1; j >= 1; --j) {
                int tmp1 = (d[i + 1][j] - dungeon[i][j - 1]) > 0 ? (d[i + 1][j] - dungeon[i][j - 1]) : 1;
                int tmp2 = (d[i][j + 1] - dungeon[i - 1][j]) > 0 ? (d[i][j + 1] - dungeon[i - 1][j]) : 1;
                d[i][j] = min(tmp1, tmp2);
            }
        }

        return (d[1][1] - dungeon[0][0]) > 0 ? (d[1][1] - dungeon[0][0]) : 1;
    }
};

当然本题还存在优化空间的办法,参考了leetCode all in one