AlgoInsight

DSA problem

Dungeon Game

Hard2D Grid DPPattern: 2D Grid DPtop600AmazonMicrosoftGoogleAppleBloomberg

A knight starts at the top-left of an m x n dungeon and wants to reach the princess at the bottom-right. The dungeon's cells contain integers: negative values are damage (monsters), positive values are healing (potions), and zero is empty. The knight's health must stay strictly positive at all times — if it drops to 0 or below at any cell (including the start and the end), the knight dies. He moves only right or down. Return the minimum initial health he needs to guarantee a safe arrival.

A common wrong approach is a top-down DP that maximizes the running sum: pick the path that loses the least, then return 1 - min_prefix. This fails because choosing the path with the highest minimum prefix is not the same as choosing the path that requires the smallest starting health — the same sum can arrive via different trajectories, and what matters is the worst dip.

The clean technique is bottom-up DP starting from the destination. Let dp[i][j] = the minimum health the knight needs upon entering cell (i, j) to survive from there to the end. At the destination he must end with at least 1 health, so dp[m - 1][n - 1] = max(1, 1 - dungeon[m - 1][n - 1]). For any other cell, after stepping in he'll then move to (i + 1, j) or (i, j + 1) — whichever needs less. So he must enter with enough health that after applying dungeon[i][j] he still has at least min(dp[i + 1][j], dp[i][j + 1]). That gives dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]).

The max(1, ...) clamp enforces the rule that health must stay positive. Compress to a single 1-D array of length n since the recurrence only reads "below" and "right." Total: O(m * n) time and O(n) space. The answer is dp[0][0].

Examples

Example 1
Input: dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]
Output: 7
Explanation: Starting with 7 HP, the knight survives the path right-right-down-down with health staying positive throughout.
Example 2
Input: dungeon = [[0]]
Output: 1
Explanation: A single empty cell still requires 1 HP to end positive.
Example 3
Input: dungeon = [[100]]
Output: 1
Explanation: Even with a strong potion at the only cell, the entry health must already be at least 1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraydynamic-programmingmatrix

Browse all DSA problems