sagelearnai

Dungeon Game

Difficulty: Hard · Pattern: 2-D Dynamic Programming · LeetCode #174

A knight starts at the top-left of dungeon and must reach the princess at the bottom-right, moving only right or down. Each cell adds dungeon[r][c] to the knight's health (negative = damage). Health must stay ≥ 1 at all times. Return the minimum starting health.

Example

text
[[-2,-3,3],
 [-5,-10,1],
 [10,30,-5]]   →  7    (path right → right → down → down)

Hints

  1. A forward DP fails: you'd have to track two competing quantities (the current health and the minimum health so far).
  2. Go backwards: how much health do you need when entering cell (r,c) so that you can finish from there?

Approach

need[r][c] = the minimum health on entering (r, c) that is enough to reach the princess:

text
need[r][c] = max(1, min(need[r+1][c], need[r][c+1]) - dungeon[r][c])

Use need = 1 "just past" the princess, i.e. at positions (R, C−1) and (R−1, C), and ∞ elsewhere outside the grid. max(1, …) encodes "health must stay at least 1", and a large positive cell can't bank health for earlier damage. Rolling 1-D: O(R·C) time, O(C) space.

The lesson: pick the DP direction where the state is self-contained.

Complexity

Time: O(R·C). Space: O(C).

Python solution
def calculateMinimumHP(dungeon):
    R, C = len(dungeon), len(dungeon[0])
    INF = float('inf')
    need = [INF] * (C + 1)
    need[C - 1] = 1
    for r in range(R - 1, -1, -1):
        for c in range(C - 1, -1, -1):
            need[c] = max(1, min(need[c], need[c + 1]) - dungeon[r][c])
        need[C] = INF
    return need[0]
JavaScript solution
function calculateMinimumHP(dungeon) {
  const R = dungeon.length, C = dungeon[0].length;
  const need = Array.from({ length: R + 1 }, () => new Array(C + 1).fill(Infinity));
  need[R][C - 1] = need[R - 1][C] = 1;
  for (let r = R - 1; r >= 0; r--) for (let c = C - 1; c >= 0; c--)
    need[r][c] = Math.max(1, Math.min(need[r + 1][c], need[r][c + 1]) - dungeon[r][c]);
  return need[0][0];
}