Dungeon Game
Hard
Topics
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
Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] Output: 7
Example 2
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
- Allocate
dpwith one extra row and column, filled with infinity, so out-of-bounds moves are never chosen by theminwithout needing bounds checks. - Seed the two cells adjacent to the exit —
dp[R][C-1]anddp[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. - Fill from the bottom-right to the top-left, applying
dp[i][j] = max(1, min(down, right) - grid[i][j]). - 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 7Two 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
maxof the two onward requirements instead ofmin. The knight chooses the route, so we want the cheaper one;maxanswers "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]import java.util.*;
class Solution {
public int calculateMinimumHP(int[][] grid) {
int R = grid.length, C = grid[0].length;
final int INF = Integer.MAX_VALUE;
int[][] dp = new int[R + 1][C + 1];
for (int[] row : dp) Arrays.fill(row, INF);
dp[R][C - 1] = 1;
dp[R - 1][C] = 1;
for (int i = R - 1; i >= 0; i--) {
for (int j = C - 1; j >= 0; j--) {
int need = Math.min(dp[i + 1][j], dp[i][j + 1]) - grid[i][j];
dp[i][j] = need <= 0 ? 1 : need;
}
}
return dp[0][0];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int calculateMinimumHP(vector<vector<int>>& grid) {
int R = grid.size(), C = grid[0].size();
const int INF = INT_MAX;
vector<vector<int>> dp(R + 1, vector<int>(C + 1, INF));
dp[R][C - 1] = 1;
dp[R - 1][C] = 1;
for (int i = R - 1; i >= 0; i--) {
for (int j = C - 1; j >= 0; j--) {
int need = min(dp[i + 1][j], dp[i][j + 1]) - grid[i][j];
dp[i][j] = need <= 0 ? 1 : need;
}
}
return dp[0][0];
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var calculateMinimumHP = function(grid) {
const R = grid.length, C = grid[0].length, INF = Infinity;
const dp = Array.from({length: R + 1}, () => new Array(C + 1).fill(INF));
dp[R][C - 1] = 1;
dp[R - 1][C] = 1;
for (let i = R - 1; i >= 0; i--) {
for (let j = C - 1; j >= 0; j--) {
const need = Math.min(dp[i + 1][j], dp[i][j + 1]) - grid[i][j];
dp[i][j] = need <= 0 ? 1 : need;
}
}
return dp[0][0];
};