Dungeon Game (LeetCode 174): Solution and Explanation
A knight starts in the top-left room of a grid and must reach the bottom-right room, moving only right or down. Each room adds or subtracts health, and if health ever drops to 0 or below the knight dies. Find the minimum starting health that guarantees he arrives alive.
Watch it run step by step
Try your own input and write the code →Intuition
A natural first instinct is to run a forward DP from the start, tracking the best health so far. That fails because two quantities matter at once: the current health and the lowest point the health hit along the way. A path that ends with lots of health might have dipped dangerously low early, and a forward table cannot decide which one to keep.
Turn the question around and work backward from the princess. Define dp[i][j] as the minimum health the knight must have when entering room (i, j) so that he can finish alive. Once you know that for the two rooms after it, the decision is easy: go toward whichever successor needs less health, then subtract this room's value, since a potion lowers the requirement and a demon raises it.
There is one more constraint. Health can never be allowed to fall below 1, so if a big potion makes the requirement zero or negative, clamp it to 1. The sentinel cells outside the grid are infinity, except the two neighbors of the princess's room, which are set to 1 so that the last room is computed with the same formula as every other room.
Approach: Bottom-up DP from the destination
- Build an
(m + 1)by(n + 1)table filled with infinity so the extra row and column act as walls. - Set
dp[m][n-1]anddp[m-1][n]to 1, meaning the knight needs at least 1 health after leaving the final room. - Iterate
ifromm - 1down to 0 andjfromn - 1down to 0. - Compute
need = min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j], the health required on entry to move into the cheaper successor. - Store
dp[i][j] = max(1, need), since the knight must always have at least 1 health. - Return
dp[0][0].
Step-by-step example
dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]
- Bottom-right room:
min(1, 1) - (-5) = 6, sodp[2][2] = 6. - Bottom row moving left:
dp[2][1] = max(1, 6 - 30) = 1anddp[2][0] = max(1, 1 - 10) = 1. The big potions make these rooms safe with health 1. - Middle row:
dp[1][2] = max(1, 6 - 1) = 5,dp[1][1] = min(1, 5) + 10 = 11,dp[1][0] = min(1, 11) + 5 = 6. - Top row:
dp[0][2] = 5 - 3 = 2,dp[0][1] = min(11, 2) + 3 = 5,dp[0][0] = min(6, 5) + 2 = 7. - The answer is 7: the knight goes right, right, down, down, and his health never drops below 1.
Code: Python, Java, C++
1class Solution:
2 def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
3 m, n = len(dungeon), len(dungeon[0])
4 dp = [[float('inf')] * (n + 1) for _ in range(m + 1)]
5 dp[m][n - 1] = dp[m - 1][n] = 1
6
7 for i in range(m - 1, -1, -1):
8 for j in range(n - 1, -1, -1):
9 need = min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]
10 dp[i][j] = max(1, need)
11
12 return dp[0][0]1class Solution {
2 public int calculateMinimumHP(int[][] dungeon) {
3 int m = dungeon.length, n = dungeon[0].length;
4 int[][] dp = new int[m + 1][n + 1];
5 for (int[] row : dp) Arrays.fill(row, Integer.MAX_VALUE);
6 dp[m][n - 1] = dp[m - 1][n] = 1;
7
8 for (int i = m - 1; i >= 0; i--) {
9 for (int j = n - 1; j >= 0; j--) {
10 int need = Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j];
11 dp[i][j] = Math.max(1, need);
12 }
13 }
14
15 return dp[0][0];
16 }
17}1class Solution {
2public:
3 int calculateMinimumHP(vector<vector<int>>& dungeon) {
4 int m = dungeon.size(), n = dungeon[0].size();
5 vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MAX));
6 dp[m][n - 1] = dp[m - 1][n] = 1;
7
8 for (int i = m - 1; i >= 0; i--) {
9 for (int j = n - 1; j >= 0; j--) {
10 int need = min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j];
11 dp[i][j] = max(1, need);
12 }
13 }
14
15 return dp[0][0];
16 }
17};Time and space complexity
O(m × n)
Each room is computed once with a constant amount of work.
O(m × n)
The table has (m + 1) × (n + 1) cells. A single row of length n + 1 would be enough, since each row only reads the row below it.
Other approaches
Binary search on starting health (time O(m × n × log H), space O(m × n))
Guess a starting health, simulate a forward DP that keeps the maximum surviving health per room, and binary search for the smallest guess that reaches the end. It works but adds a log factor over the range of health values.
One-dimensional DP (time O(m × n), space O(n))
Same backward recurrence but stored in one array of length n + 1, updating it in place for each row from bottom to top.
Common mistakes
- Running the DP forward from the top-left. Forward DP cannot capture both the current health and the minimum along the path, so it gives wrong answers on many grids.
- Forgetting the clamp to at least 1. Without it a large potion produces a requirement of 0 or less, which would let the knight enter with no health.
- Initializing all sentinel cells to 1 instead of infinity. Then the knight could appear to step off the grid, and rooms on the edges would get requirements that are too low.
- Returning
dp[0][0] + 1or adding 1 elsewhere. The clamp to 1 already includes the rule that health must stay positive.
Frequently asked questions
Why does Dungeon Game need DP from the bottom-right?
Because the requirement at a room depends on what lies ahead, not on what came before. Working backward lets each cell summarize the minimum health needed for the rest of the trip, so a simple min picks the better direction.
Why is the answer max(1, need)?
The knight must always have at least 1 health. When a room gives a big potion, need can become zero or negative, but he still needs 1 health to be alive when he enters.
What is the time complexity of Dungeon Game?
O(m × n), since every room is filled once using its right and lower neighbors.
Can Dungeon Game be solved with Dijkstra?
Not cleanly, because the cost is the minimum prefix sum along a path rather than a sum of edge weights. The backward DP is the standard, simpler solution.