Skip to content

Commit 6953277

Browse files
author
applewjg
committed
Dungeon Game
Change-Id: I7d0c8e685505b6ebadc8e55b0e4088a76f29a71c
1 parent e7b2d56 commit 6953277

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

DungeonGame.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Author: King, [email protected]
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+
33+
public class Solution {
34+
public int calculateMinimumHP(int[][] dungeon) {
35+
int M = dungeon.length;
36+
if (M == 0) return 0;
37+
int N = dungeon[0].length;
38+
int[][] dp = new int[M][N];
39+
dp[M-1][N-1] = 1 - Math.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 = Math.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 Math.max(1,dp[0][0]);
56+
}
57+
}

0 commit comments

Comments
 (0)