8000 Dungeon Game · leetcoders/LeetCode@993bfe2 · GitHub
[go: up one dir, main page]

Skip to content

Commit 993bfe2

Browse files
author
applewjg
committed
Dungeon Game
Change-Id: I1c23d3ae7c4273cdb941bb67b0b3ab645cb8a440
1 parent 11fb308 commit 993bfe2

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

DungeonGame.h

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Author: King, wangjingui@outlook.com
3+
Date: Jan 6, 2015
4+
Problem: Dungeon Game
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/dungeon-game/
7+
Notes:
8+
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.
9+
10+
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.
11+
12+
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).
13+
14+
In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
15+
16+
17+
Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.
18+
19+
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.
20+
21+
-2 (K) -3 3
22+
-5 -10 1
23+
10 30 -5 (P)
24+
25+
Notes:
26+
27+
The knight's health has no upper bound.
28+
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.
29+
30+
Solution: ...
31+
*/
32+
class Solution {
33+
public:
34+
int calculateMinimumHP(vector<vector<int> > &dungeon) {
35+
int M = dungeon.size(), res = 0;
36+
if (M == 0) return res;
37+
int N = dungeon[0].size();
38+
vector<vector<int>> dp(M, vector<int>(N,0));
39+
dp[M-1][N-1] = 1 - min(0, dungeon[M-1][N-1]);
40+
for (int i = M - 2; i >= 0; --i) {
41+
if (dp[i+1][N-1] - dungeon[i][N-1] < 0) dp[i][N-1] = 1;
42+
else dp[i][N-1] = dp[i+1][N-1] - dungeon[i][N-1];
43+
}
44+
for (int j = N - 2; j >= 0; --j) {
45+
if (dp[M-1][j+1] - dungeon[M-1][j] < 0) dp[M-1][j] = 1;
46+
else dp[M-1][j] = dp[M-1][j+1] - dungeon[M-1][j];
47+
}
48+
for (int i = M - 2; i >= 0; --i) {
49+
for (int j = N - 2; j >= 0; --j) {
50+
int val = min(dp[i+1][j], dp[i][j+1]);
51+
if (dungeon[i][j] > val) dp[i][j] = 1;
52+
else dp[i][j] = val - dungeon[i][j];
53+
}
54+
}
55+
return max(1,dp[0][0]);
56+
}
57+
};

0 commit comments

Comments
 (0)
0