Skip to content

Commit 6b0ffd9

Browse files
authored
Create DungeonGame.java
The DungeonGame class implements a solution to the Dungeon Game problem using dynamic programming. The goal is to determine the minimum initial health points needed for a knight to survive a dungeon represented by a 2D grid, where each cell contains a health value that can be positive or negative. The knight moves from the top-left corner to the bottom-right corner, and the solution calculates the minimum health required to ensure the knight's health never drops to zero or below at any point.
1 parent 3b2ba48 commit 6b0ffd9

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
3+
public class DungeonGame {
4+
5+
public static int calculateMinimumHP(int[][] dungeon) {
6+
int m = dungeon.length;
7+
int n = dungeon[0].length;
8+
int[][] dp = new int[m][n];
9+
10+
dp[m - 1][n - 1] = Math.max(1, 1 - dungeon[m - 1][n - 1]);
11+
12+
for (int i = m - 2; i >= 0; i--) {
13+
dp[i][n - 1] = Math.max(1, dp[i + 1][n - 1] - dungeon[i][n - 1]);
14+
}
15+
16+
for (int j = n - 2; j >= 0; j--) {
17+
dp[m - 1][j] = Math.max(1, dp[m - 1][j + 1] - dungeon[m - 1][j]);
18+
}
19+
20+
for (int i = m - 2; i >= 0; i--) {
21+
for (int j = n - 2; j >= 0; j--) {
22+
int minHealthOnExit = Math.min(dp[i + 1][j], dp[i][j + 1]);
23+
dp[i][j] = Math.max(1, minHealthOnExit - dungeon[i][j]);
24+
}
25+
}
26+
27+
return dp[0][0];
28+
}
29+
30+
public static void main(String[] args) {
31+
int[][] dungeon = {
32+
{ -2, -3, 3 },
33+
{ -5, -10, 1 },
34+
{ 10, 30, -5 }
35+
};
36+
System.out.println(calculateMinimumHP(dungeon)); // Output: 7
37+
}
38+
}

0 commit comments

Comments
 (0)