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.

header 1 header 2 header 3
-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.

https://discuss.leetcode.com/topic/6906/who-can-explain-why-from-the-bottom-right-corner-to-left-top

Who can explain why “from the bottom right corner to left top.”

Why we fill the table from the bottom right corner to left top?


https://discuss.leetcode.com/topic/6912/c-dp-solution

C++ DP solution

第一点,从右下角开始思考,从右下角开始思考。

同时注意,knight在路途中间不能没有血。

Use hp[i][j] to store the min hp needed at position (i, j), then do the calculation from right-bottom to left-up.

Note: adding dummy row and column would make the code cleaner.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int calculateMinimumHP(vector<vector<int> > &dungeon) {
int M = dungeon.size();
int N = dungeon[0].size();
// hp[i][j] represents the min hp needed at position (i, j)
// Add dummy row and column at bottom and right side
vector<vector<int> > hp(M + 1, vector<int>(N + 1, INT_MAX));
hp[M][N - 1] = 1;
hp[M - 1][N] = 1;
for (int i = M - 1; i >= 0; i--) {
for (int j = N - 1; j >= 0; j--) {
int need = min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j];
hp[i][j] = need <= 0 ? 1 : need;
}
}
return hp[0][0];
}
};

https://discuss.leetcode.com/topic/6912/c-dp-solution/4

We could reduce the 2-D DP matrix into 1-D

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dungeon) {
int n=dungeon.size(),m=dungeon[0].size();
vector<int> dp(n+1,INT_MAX);
dp[n-1]=1;
for(int j=m-1;j>=0;j--){
for(int i=n-1;i>=0;i--){
dp[i]=min(dp[i],dp[i+1])-dungeon[i][j];
dp[i]=max(1,dp[i]);
}
}
return dp[0];
}
};

https://discuss.leetcode.com/topic/7633/best-solution-i-have-found-with-explanations

Best solution I have found with explanations

http://leetcodesolution.blogspot.com/2015/01/leetcode-dungeon-game.html

seems pretty simple… and easy to understand explanations…

It is easy to know that at grid P, since “ at any point his health point drops to 0 or below, he dies immediately”, the remaining health value should be at least 1, that is, initialHealth + dungeon >= 1, we have initialHealth = max(1, 1 - dungeon[i][j]). (Notice, at any grid, the initial health should be at least 1 (for example, test case [1,0,0] require initial health 1 even though it has positive remaining health at grid[0][1] and grid[0][2])

Similarly, to satisfy the initial health of dungeon[i][j], the initial health of dungeon[i-1][j] (or dungeon[i][j-1]) should be at least initialHealth[i-1][j] + dungeon[i-1][j] = initialHealth[i][j], that is, initialHealth[i][j] = initialHealth[i][j] - dungeon[i-1][j].

In addition, if grid[i][j] can go both grid[i+1][j] and grid[i][j+1] to P, we should choose a path with less initial health between grid[i+1][j] and grid[i][j+1] since it require less initial health of grid[i][j].
We can simply code the solution by having the dynamic programming equations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int calculateMinimumHP(vector &dungeon) {
int m = dungeon.size();
int n = dungeon[0].size();
vector minInitHealth(m, vector<int>(n,0));
for(int i=m-1; i>=0; i--)
{
for (int j=n-1; j>=0; j--)
{
if (i == m-1 && j == n-1)
{
minInitHealth[i][j] = max(1, 1 - dungeon[i][j]);
}
else if (i == m-1)
{
minInitHealth[i][j] = max(1, minInitHealth[i][j+1] - dungeon[i][j]);
}
else if (j == n-1)
{
minInitHealth[i][j] = max(1, minInitHealth[i+1][j] - dungeon[i][j]);
}
else
{
minInitHealth[i][j] = max(1, min(minInitHealth[i+1][j],minInitHealth[i][j+1]) - dungeon[i][j]);
}
}
}

return minInitHealth[0][0];
}

https://discuss.leetcode.com/topic/7024/sharing-my-solution-with-o-n-space-o-mn-runtime

Sharing my solution with O(n) space, O(mn) runtime

Here is my solution using dp and rolling array –Dungeon Game:

1
2
3
4
5
6
7
8
9
10
11
12
13
int calculateMinimumHP(vector<vector<int> > &dungeon) {
const int m = dungeon.size();
const int 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] = getMin(min(dp[j], dp[j + 1]) - dungeon[i][j]);
return dp[0];
}
int getMin(int n){
return n <= 0 ? 1 : n;
}

Note: Update from right to left and from bottom up.


https://discuss.leetcode.com/topic/19304/6-lines-16-ms-c-o-mn-time-o-n-space

6 lines, 16 ms, C++, O(mn) Time, O(n) Space,

1
2
3
4
5
6
7
8
9
10
struct Solution {
int calculateMinimumHP(vector<vector<int>>& d) {
vector<int> dp(d.size() + 1, INT_MAX);
dp[d.size() - 1] = 1;
for (int i = d[0].size() - 1; i >= 0; --i)
for (int j = d.size() - 1; j >= 0; --j)
dp[j] = max(1, min(dp[j + 1], dp[j]) - d[j][i]);
return dp[0];
}
};

https://discuss.leetcode.com/topic/26511/a-12-ms-c-solution-dp

A 12 ms C++ solution, DP

This problem is quite like #64 Minimum Path Sum.

The trick is where is the Starting point. This problem ask us to find the least hp in top-left. So in the most optimistic situation, bottom-right value can be determined as 1. Then bottom-right is the starting point.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int calculateMinimumHP(vector<vector<int>>& dun) 
{
if (!dun.size() || !dun[0].size())
return 1;
int nrow = dun.size();
int ncol = dun[0].size();
vector<int> row(ncol + 1, INT_MAX);
row[ncol - 1] = 1;
int i, j, t;
for (i = nrow - 1; i >= 0; --i)
{
for (j = ncol - 1; j >= 0; --j)
{
t = min(row[j], row[j + 1]) - dun[i][j];
row[j] = max(t, 1); //row[j]=smaller value from below and right, but no smaller than 1.
}
}
return row[0];
}

https://discuss.leetcode.com/topic/19179/6-lines-python-8-lines-ruby

6 lines Python, 8 lines Ruby

Just some DP.

Python

1
2
3
4
5
6
7
def calculateMinimumHP(self, dungeon):
n = len(dungeon[0])
need = [2**31] * (n-1) + [1]
for row in dungeon[::-1]:
for j in range(n)[::-1]:
need[j] = max(min(need[j:j+2]) - row[j], 1)
return need[0]

Got accepted in 52 ms, faster than all other recent Python submissions (best was 56 ms, achieved by 5.7692%).

谢谢你,可爱的朋友。