LeetCode – Dungeon Game (Java)

Example:

-2 (K)	-3	3
-5	-10	1
10	30	-5 (P)

Java Solution

This problem can be solved by using dynamic programming. We maintain a 2-D table. h[i][j] is the minimum health value before he enters (i,j). h[0][0] is the value of the answer. The left part is filling in numbers to the table.

public int calculateMinimumHP(int[][] dungeon) {
	int m = dungeon.length;
	int n = dungeon[0].length;
 
	//init dp table
	int[][] h = new int[m][n];
 
	h[m - 1][n - 1] = Math.max(1 - dungeon[m - 1][n - 1], 1);
 
	//init last row
	for (int i = m - 2; i >= 0; i--) {
		h[i][n - 1] = Math.max(h[i + 1][n - 1] - dungeon[i][n - 1], 1);
	}
 
	//init last column
	for (int j = n - 2; j >= 0; j--) {
		h[m - 1][j] = Math.max(h[m - 1][j + 1] - dungeon[m - 1][j], 1);
	}
 
	//calculate dp table
	for (int i = m - 2; i >= 0; i--) {
		for (int j = n - 2; j >= 0; j--) {
			int down = Math.max(h[i + 1][j] - dungeon[i][j], 1);
			int right = Math.max(h[i][j + 1] - dungeon[i][j], 1);
			h[i][j] = Math.min(right, down);
		}
	}
 
	return h[0][0];
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Ing

    Got here from google and I can see an answer, but not the problem it answers…

  • omnomnipotent

    Thank you Stellari – you would think that this information would be presented up front. To Programcreek – don’t assume that everyone knows what this type of problem is; a simple explanation would do and save trouble for everyone.

  • Candis

    Loved the answer! 🙂

  • typing..

    Attempt this problem if you want to brush up your DP concepts.. Very Nice problem.. and even perfect solution.. Thumbs Up 🙂

  • stellari

    The purpose of the game is for a Knight(K) to traverse a dungeon full of threats and power-ups to rescue the princess(P). You can find the full problem description on oj.leetcode.com in the problem “Dungeon Game”. It is not surprising you can’t find the problem because I (yes, I am the creator of this problem on leetcode) wrote the original problem description in my own language, and apparently it hasn’t gain enough popularity on the web yet.

  • Arnaud Hebert

    Is it possible to have more information about the game itself? (the purpose of the game, the meaning of the numbers, meaning of K, meaning of P). I was not able to look it up online