Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers).
To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
Return the knight's minimum initial health so that he can rescue the princess.
Note that any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.
Example 1:
Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]] Output: 7 Explanation: The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.
Example 2:
Input: dungeon = [[0]] Output: 1
Constraints:
m == dungeon.lengthn == dungeon[i].length1 <= m, n <= 200-1000 <= dungeon[i][j] <= 1000Problem summary: The demons had captured the princess and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of m x n rooms laid out in a 2D grid. Our valiant knight was initially positioned in the top-left room and must fight his way through dungeon to rescue the princess. The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. Some of the rooms are guarded by demons (represented by negative integers), so the knight loses health upon entering these rooms; other rooms are either empty (represented as 0) or contain magic orbs that increase the knight's health (represented by positive integers). To reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. Return the knight's minimum initial health so that he can rescue the princess.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[[-2,-3,3],[-5,-10,1],[10,30,-5]]
[[0]]
unique-paths)minimum-path-sum)cherry-pickup)minimum-path-cost-in-a-grid)minimum-health-to-beat-game)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #174: Dungeon Game
class Solution {
public int calculateMinimumHP(int[][] dungeon) {
int m = dungeon.length, n = dungeon[0].length;
int[][] dp = new int[m + 1][n + 1];
for (var e : dp) {
Arrays.fill(e, 1 << 30);
}
dp[m][n - 1] = dp[m - 1][n] = 1;
for (int i = m - 1; i >= 0; --i) {
for (int j = n - 1; j >= 0; --j) {
dp[i][j] = Math.max(1, Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
}
}
return dp[0][0];
}
}
// Accepted solution for LeetCode #174: Dungeon Game
func calculateMinimumHP(dungeon [][]int) int {
m, n := len(dungeon), len(dungeon[0])
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, n+1)
for j := range dp[i] {
dp[i][j] = 1 << 30
}
}
dp[m][n-1], dp[m-1][n] = 1, 1
for i := m - 1; i >= 0; i-- {
for j := n - 1; j >= 0; j-- {
dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1])-dungeon[i][j])
}
}
return dp[0][0]
}
# Accepted solution for LeetCode #174: Dungeon Game
class Solution:
def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
m, n = len(dungeon), len(dungeon[0])
dp = [[inf] * (n + 1) for _ in range(m + 1)]
dp[m][n - 1] = dp[m - 1][n] = 1
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j])
return dp[0][0]
// Accepted solution for LeetCode #174: Dungeon Game
struct Solution;
impl Solution {
fn calculate_minimum_hp(dungeon: Vec<Vec<i32>>) -> i32 {
let n = dungeon.len();
let m = dungeon[0].len();
let mut dp = vec![vec![0; m]; n];
for i in (0..n).rev() {
for j in (0..m).rev() {
if i + 1 < n && j + 1 < m {
dp[i][j] = 1.max(-dungeon[i][j] + dp[i + 1][j].min(dp[i][j + 1]));
continue;
}
if i + 1 < n {
dp[i][j] = 1.max(-dungeon[i][j] + dp[i + 1][j]);
continue;
}
if j + 1 < m {
dp[i][j] = 1.max(-dungeon[i][j] + dp[i][j + 1]);
continue;
}
dp[i][j] = 1.max(-dungeon[i][j] + 1);
}
}
dp[0][0]
}
}
#[test]
fn test() {
let dungeon = vec_vec_i32![[-2, -3, 3], [-5, -10, 1], [10, 30, -5]];
let res = 7;
assert_eq!(Solution::calculate_minimum_hp(dungeon), res);
}
// Accepted solution for LeetCode #174: Dungeon Game
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #174: Dungeon Game
// class Solution {
// public int calculateMinimumHP(int[][] dungeon) {
// int m = dungeon.length, n = dungeon[0].length;
// int[][] dp = new int[m + 1][n + 1];
// for (var e : dp) {
// Arrays.fill(e, 1 << 30);
// }
// dp[m][n - 1] = dp[m - 1][n] = 1;
// for (int i = m - 1; i >= 0; --i) {
// for (int j = n - 1; j >= 0; --j) {
// dp[i][j] = Math.max(1, Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
// }
// }
// return dp[0][0];
// }
// }
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.