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]
assert Solution().calculateMinimumHP([[-2, -3, 3], [-5, -10, 1], [10, 30, -5]]) == 7
assert Solution().calculateMinimumHP([[0]]) == 1
class Solution {
public int calculateMinimumHP(int[][] dungeon) {
int R = dungeon.length, C = dungeon[0].length;
int[] need = new int[C + 1];
Arrays.fill(need, Integer.MAX_VALUE);
need[C - 1] = 1;
for (int r = R - 1; r >= 0; r--)
for (int c = C - 1; c >= 0; c--)
need[c] = Math.max(1, Math.min(need[c], need[c + 1]) - dungeon[r][c]);
return need[0];
}
}
func calculateMinimumHP(dungeon [][]int) int {
R, C := len(dungeon), len(dungeon[0])
need := make([]int, C+1) // health needed on entering each cell, computed from the bottom right
for c := range need {
need[c] = math.MaxInt / 2
}
need[C-1] = 1 // virtual cell after the princess
for r := R - 1; r >= 0; r-- {
for c := C - 1; c >= 0; c-- {
need[c] = max(1, min(need[c], need[c+1])-dungeon[r][c])
}
}
return need[0]
}