SDE & MLE Prep

174. Dungeon Game

Problem

A knight starts at the top-left room of the dungeon grid and must reach the princess in the bottom-right, moving only right or down. Each room adds its value (negative: damage, positive: healing) to his health, and he dies if it ever drops to 0 or below. Return the minimum starting health needed.

Example: [[-2,-3,3],[-5,-10,1],[10,30,-5]] → 7

Forward DP fails (you'd need to track both current and minimum health). Go backwards from the princess: need[r][c] = max(1, min(need[r+1][c], need[r][c+1]) − dungeon[r][c]).

Complexity: O(m·n).

class Solution:
    def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
        R, C = len(dungeon), len(dungeon[0])
        INF = float("inf")
        need = [INF] * (C + 1)
        need[C - 1] = 1                                   # virtual cell after the princess
        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])
        return need[0]