Dungeon Game

Hard

Topics
ArrayDynamic ProgrammingMatrix

A knight starts at the top-left cell of grid and must reach the bottom-right cell, moving only right or down. Each cell adds its value to the knight's health (negative values are demons, positive are potions). The knight dies if health drops to 0 or below at any point. Return the minimum initial health needed to survive the journey.

Example 1

0-2-331-5-10121030-5012
the route taken
Moves go only right and down, and the numbers are added to the knight’s health as he lands on them — negative cells cost, positive cells heal. He dies the moment health reaches 0, including part-way along a route, which is why a route’s total is not enough on its own. The answer is the smallest starting health that survives the best route: 7.
2D grid — one row per line.
Input:  dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]
Output: 7

Example 2

000
the route taken
Input:  dungeon = [[0]]
Output: 1

Constraints

  • 1 <= rows, cols <= 200
  • -1000 <= grid[i][j] <= 1000
Editorial — intuition, approach, complexity and pitfalls

Intuition

The obvious move is to walk forward from the top-left, tracking health as you go, and that is exactly what does not work here. It is worth understanding why, because the failure is instructive rather than incidental.

Walking forward you would carry "health so far" and try to maximise it. But the quantity we are asked for is the starting health, and whether a starting value is sufficient depends on the worst dip anywhere along the path — which is in the future. Two partial paths arriving at the same cell are not comparable on current health alone: a path with more health now may have needed a larger initial reserve to get there, and a path with less health now may be the better prefix. There is no single number you can carry forward that makes the choice locally, so the greedy and the forward DP both break.

Flip the direction and the quantity becomes well-defined. Define dp[i][j] as the minimum health needed on entering cell (i,j) to survive from there to the end. That is a statement about the future only, so it composes: entering a cell, you will take its effect and then need enough for the cheaper of the two onward moves.

So, working backwards:

need = min(dp[i+1][j], dp[i][j+1]) - grid[i][j]
dp[i][j] = max(1, need)

The subtraction is the cell's effect — a demon (negative) raises the requirement, an orb (positive) lowers it. The max(1, ...) is the rule that health must stay strictly positive: even if a cell hands you a huge orb, you still have to walk in alive, so the requirement can never drop below 1. That clamp is also what stops a single large orb from "paying for" an arbitrarily bad stretch before it.

💡 This is the same backwards-reasoning trick as in interval scheduling or minimax game DP: when the answer depends on the worst thing still to come, define the state over the suffix rather than the prefix.

Approach

  1. Allocate dp with one extra row and column, filled with infinity, so out-of-bounds moves are never chosen by the min without needing bounds checks.
  2. Seed the two cells adjacent to the exit — dp[R][C-1] and dp[R-1][C] — to 1. This encodes "after stepping off the final cell, 1 health suffices", and makes the bottom-right corner compute correctly from the same formula as everything else.
  3. Fill from the bottom-right to the top-left, applying dp[i][j] = max(1, min(down, right) - grid[i][j]).
  4. Return dp[0][0].

Dry Run

grid = [[-2,-3,3],[-5,-10,1],[10,30,-5]], expected 7.

cell(2,2) grid=-5   min(down=1,  right=1)   - (-5) = 6   -> dp=6
cell(2,1) grid=30   min(down=inf,right=6)   - 30   = -24 -> dp=1   (clamped)
cell(2,0) grid=10   min(down=inf,right=1)   - 10   = -9  -> dp=1   (clamped)
cell(1,2) grid=1    min(down=6,  right=inf) - 1    = 5   -> dp=5
cell(1,1) grid=-10  min(down=1,  right=5)   - (-10)= 11  -> dp=11
cell(1,0) grid=-5   min(down=1,  right=11)  - (-5) = 6   -> dp=6
cell(0,2) grid=3    min(down=5,  right=inf) - 3    = 2   -> dp=2
cell(0,1) grid=-3   min(down=11, right=2)   - (-3) = 5   -> dp=5
cell(0,0) grid=-2   min(down=6,  right=5)   - (-2) = 7   -> dp=7

answer 7

Two things worth reading off this. The clamp fires at (2,1) and (2,0), where the 30 and 10 orbs would otherwise produce a negative requirement — the knight cannot bank health he has not collected yet. And at (0,0) the path chosen is to the right (requirement 5) rather than down (6), so the optimal route is right-right-down-down through the 3 and the 1, not through the big orbs at the bottom left.

Complexity

  • Time — O(rows * cols): each cell is computed once from two already-known neighbours, with constant work per cell.
  • Space — O(rows * cols): the full table as written. It only ever reads one row below and one cell to the right, so it reduces to O(cols) with a single rolling row updated right-to-left in place — worth offering, since the interviewer usually asks. The padded row and column of infinities is what buys the clean formula; without it you need explicit edge cases for the last row and column.

Common Pitfalls

  • Working forwards from the top-left. The state is not well-defined in that direction, as above. This is the single thing the problem tests.
  • Omitting the max(1, ...) clamp. Health must stay strictly positive, and without the clamp a large orb lets a negative requirement propagate, understating the answer.
  • Clamping to 0 instead of 1. Zero health is death here, not survival.
  • Taking max of the two onward requirements instead of min. The knight chooses the route, so we want the cheaper one; max answers "survive either path", which is a different question.
  • Seeding only one of the two cells past the exit, or seeding the exit itself to 1 and special-casing it. Seeding both neighbours to 1 lets the corner fall out of the general formula.
  • Adding the grid value rather than subtracting it. The requirement moves opposite to the cell's effect: a demon of -5 raises what you need by 5.

Full Solution — all languages

class Solution:
    def calculateMinimumHP(self, grid):
        R = len(grid)
        C = len(grid[0])
        INF = float('inf')
        dp = [[INF] * (C + 1) for _ in range(R + 1)]
        dp[R][C - 1] = 1
        dp[R - 1][C] = 1
        for i in range(R - 1, -1, -1):
            for j in range(C - 1, -1, -1):
                need = min(dp[i + 1][j], dp[i][j + 1]) - grid[i][j]
                dp[i][j] = 1 if need <= 0 else need
        return dp[0][0]
Asked at Flipkart Intuit
SensAI
Beta
Tap the mic to stop voice mode