Dungeon Game
Work backward from the princess to find the least health the knight must start with.
A knight starts in the top-left cell of a grid named dungeon
Example 1
Output: 7
Explanation: on the path right, right, down, down, his health goes 7 → 5 → 2 → 5 → 6 → 1.
Example 2
Output: 1
The Idea
Picture a walk through a castle where every room holds either a trap or a healing potion. You may only go right or down, and you must not run out of health in any room along the way, not even for a moment. How much health should you set out with?
Take Example 1 and the path right, right, down, down. Starting with 7, the knight loses 2 in the first room and has 5. The next room takes 3, leaving 2. Then he heals 3 and 1, reaching 6, and the princess's room takes 5, so he arrives with 1. Starting with 6 would leave him with 0 in that last room, which is too little.
Which path should he take, then? The path that gains the most is not the safest one. The path down, down, right, right passes rooms -2, -5, 10, 30 and -5. It ends 28 above its starting health, the best of all six paths, but after the second room it is 7 below the start, so it needs 8. The path right, right, down, down ends 6 below its start and never goes lower than that, so 7 is enough.
So walking forward, each path carries two numbers: the health it has now, and how low it has been. Neither one alone says which path is better. What if we start from the other end instead?
The princess's room takes 5, and the knight must still have 1 after it, so he needs 6 when he steps in. The room just above her gives 1 health, so stepping in there with 5 is enough: he gets 6 and walks on to the princess. Each room's answer depends only on the rooms that come after it, and those are already worked out.
In the picture above, the big number in each cell is its value, and under it, need is the least health the knight must have when he steps into that cell to reach the princess alive. The princess's cell, in row 2, column 2, shows need 6, and the cell above it shows need 5, as worked out above. The two dashed cells after the princess hold 1: once he is past her room, 1 health is enough.
Now look at row 2, column 1, which heals 30. The cell after it needs 6, and 30 healing covers that easily, so this cell needs just 1, the least a living knight can have. Finally, the top-left cell has two ways on: right needs 5 and down needs 6. He takes the cheaper one, right, and the -2 in his first room raises the 5 to 7, the answer.
Each need comes from the needs of the two cells after it, so they are saved in a table named needneed[i][j]ij
Solution Approach
Turning the backward walk into code means settling four things: why trying every path is too slow, the rule that fills one cell of need
Trying every path
Why not simply walk every path and keep the best start? Every path takes the same moves in some order: in a 3 by 3 dungeon, two moves right and two moves down, which gives the six paths of Example 1. In a 10 by 10 dungeon there are already 48,620 paths, and in a 20 by 20 dungeon 35,345,263,800. The table needs one entry per cell instead.
The rule for one cell
How is one entry worked out? First take nextnextnext - dungeon[i][j]
For the cell holding 1 above the princess, nextnextneed[i][j] = Math.max(1, next - dungeon[i][j])
The cells past the edge
What about cells in the bottom row, which have nothing below, or in the right column, which have nothing to their right? The table gets one extra row and one extra column, so every cell has a neighbour to read. The two extra cells right after the princess hold 1, the dashed cells in the picture.
All other extra cells hold Integer.MAX_VALUEintMath.minnextInteger.MAX_VALUE
The order of filling
Which cell comes first? A cell needs the cell below it and the cell to its right, so the rows are filled from the bottom up, and each row from right to left. The princess's cell is first, and the top-left cell, the answer, is last.
Optional: keeping one row
Each row of need
Java Solution
The method calculateMinimumHP
- First, read the number of rows into
and columns intom . Create the tablen with one extra row and column, (m + 1) by (n + 1), and fill every entry withneed usingInteger.MAX_VALUE .Arrays.fill - Set the two cells after the princess,
below her andneed[m][n - 1] to her right, to 1.need[m - 1][n] - Fill the grid with two loops, one inside the other. The outer loop moves
from the bottom row,i , up to row 0. For each row, the inner loop movesm - 1 from the right column,j , left to column 0.n - 1 - Inside, set
to the smaller ofnext andneed[i + 1][j] , then setneed[i][j + 1] toneed[i][j] .Math.max(1, next - dungeon[i][j]) - When both loops are done, return
, the health needed to step into the starting cell.need[0][0]
The main
import java.util.Arrays;
public class DungeonGame {
public static int calculateMinimumHP(int[][] dungeon) {
int m = dungeon.length;
int n = dungeon[0].length;
// need[i][j]: least health the knight must have when he steps into cell (i, j)
int[][] need = new int[m + 1][n + 1];
for (int[] row : need) {
Arrays.fill(row, Integer.MAX_VALUE); // outside the grid: never the better move
}
need[m][n - 1] = 1; // after the princess's cell, 1 health is enough
need[m - 1][n] = 1;
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
int next = Math.min(need[i + 1][j], need[i][j + 1]); // cheaper of down and right
need[i][j] = Math.max(1, next - dungeon[i][j]);
}
}
return need[0][0];
}
public static void main(String[] args) {
int[][] example1 = {{-2, -3, 3}, {-5, -10, 1}, {10, 30, -5}};
System.out.println(calculateMinimumHP(example1));
System.out.println(calculateMinimumHP(new int[][] {{0}}));
System.out.println(calculateMinimumHP(new int[][] {{-5}}));
System.out.println(calculateMinimumHP(new int[][] {{5}}));
System.out.println(calculateMinimumHP(new int[][] {{1, -3, 3}}));
System.out.println(calculateMinimumHP(new int[][] {{-1}, {50}, {-60}}));
}
}
Running it prints:
7
1
6
1
3
12
The 7 on the first line is Example 1, the same need 7 as the top-left cell of the picture, and the 1 below it is Example 2. The third line shows that a room doing 5 damage needs 6, so the knight leaves it with 1. The fourth line, 1 for a room that heals 5, is the work of Math.max(1, ...)
Without that floor, the healing room gives 1 - 5 = -4. Example 1 goes wrong as well: the impossible -24 in the cell holding 30 is carried back into the cells before it, and the method returns -27 instead of 7.
The one-row dungeon [[1, -3, 3]]
Complexity
The work is one pass over the table, with a fixed amount of work per cell.
- Time: O(m × n), because each of the m × n rooms gets its need once from two neighbours, and filling the extra row and column adds only m + n + 1 entries.
- Space: O(m × n), because the
table holds (m + 1) × (n + 1) entries, and keeping a single row of it brings this down to O(n).need
When only the total along the path matters, with no health floor along the way, the table can be filled forward from the start: see