Dungeon Game (LeetCode 174): Solution and Explanation

Hard
Array
Dynamic Programming
Matrix

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Build an (m + 1) by (n + 1) table filled with infinity so the extra row and column act as walls.
  2. Set dp[m][n-1] and dp[m-1][n] to 1, meaning the knight needs at least 1 health after leaving the final room.
  3. Iterate i from m - 1 down to 0 and j from n - 1 down to 0.
  4. 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.
  5. Store dp[i][j] = max(1, need), since the knight must always have at least 1 health.
  6. Return dp[0][0].

Step-by-step example

dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]
  1. Bottom-right room: min(1, 1) - (-5) = 6, so dp[2][2] = 6.
  2. Bottom row moving left: dp[2][1] = max(1, 6 - 30) = 1 and dp[2][0] = max(1, 1 - 10) = 1. The big potions make these rooms safe with health 1.
  3. 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.
  4. Top row: dp[0][2] = 5 - 3 = 2, dp[0][1] = min(11, 2) + 3 = 5, dp[0][0] = min(6, 5) + 2 = 7.
  5. 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]

Time and space complexity

Time

O(m × n)

Each room is computed once with a constant amount of work.

Space

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] + 1 or 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.