Skip to content

0174. 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.

Analysis

For each cell, we have three requirements fullfill:

HP is short for health

  1. HP > 0
  2. HP + w[i][j + 1] > 0 if you want to move right
  3. HP + w[i + 1][j] > 0 if you want to move downward

However, you don't need to satisfy case 2 and case 3 at the same time, and you should always choose the direction that could make you easier to reach to your goal. What I mean by "easier" is that HP is the least in all three cases.

So we can define a f 2D array that represents the minimal health for each cell. To find out the initial minimal health, we just return f[0][0], and using the rules we have defined previously, the induction rule is:

f[i][j]=min(1,f[i][j]-w[i][j+1],f[i][j]-w[i+1][j])

After resolving all the edge cases, we can return our answer.

  • Time: O(m \times n)
  • Space: O(m \times n)

Code

class Solution {
public:
    int calculateMinimumHP(vector<vector<int>>& d) {
        int res = INT_MAX, m = d.size(), n = d[0].size();
        vector<vector<int>> f(m, vector<int>(n, INT_MAX));
        for (int i = m - 1; i >= 0; --i)
            for (int j = n - 1; j >= 0; --j) {
                // this is the starting point
                if (i == m - 1 && j == n - 1) f[i][j] = max(1, 1 - d[i][j]);
                else {
                    // check right
                        if (i + 1 < m) f[i][j] = f[i + 1][j] - d[i][j];
                    // check down
                    if (j + 1 < n) f[i][j] = min(f[i][j], f[i][j + 1] - d[i][j]);
                    // check 1
                    f[i][j] = max(1, f[i][j]);
                }
            }
        return f[0][0];
    }
};

Last update: April 1, 2022