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 Overview: You are given a 2D dungeon grid where each cell either damages or heals the knight. The knight starts at the top-left and must reach the bottom-right to rescue the princess, moving only right or down. The challenge is computing the minimum initial health required so the knight never drops to 0 or below at any point along the path.
Approach 1: Dynamic Programming from Bottom-Right (O(m*n) time, O(m*n) space)
The key insight is to work backward from the destination instead of forward from the start. At each cell, you compute the minimum health required to enter that cell so the knight can safely reach the princess. Create a DP table where dp[i][j] stores the minimum health needed before stepping into cell (i, j). The transition chooses the better of the two possible next moves: right or down. You calculate minHealthNeeded = min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j], then clamp it to at least 1 because health must always remain positive. Iterating from the bottom-right to the top-left ensures all dependencies are already computed. This approach directly models the survival constraint and works well for grid problems involving path decisions in a matrix with cumulative effects.
Approach 2: Space Optimized Dynamic Programming (O(m*n) time, O(n) space)
The 2D DP table can be reduced to a single row because each state depends only on the current row and the row below it. Use a 1D array where dp[j] represents the minimum health required to enter the current cell in that column. Iterate from the bottom row upward and from right to left within each row. Update each entry using the same recurrence: choose the smaller required health from the right or downward move, subtract the current dungeon value, and ensure the result is at least 1. This reduces memory usage from O(m*n) to O(n) while preserving the same transition logic. Space optimization like this is common in dynamic programming problems where each state only depends on a limited set of neighbors.
The difficulty comes from recognizing that forward simulation fails because you don't know how much health you must reserve for future damage. Reversing the perspective solves that uncertainty.
Recommended for interviews: The bottom-up dynamic programming solution is what most interviewers expect. It clearly shows understanding of grid-based array transitions and optimal substructure. The space-optimized version is a strong follow-up that demonstrates deeper mastery of DP state reduction.
In this approach, we'll utilize dynamic programming to calculate the minimum health needed at each room starting from the bottom-right corner (princess's location) up to the top-left corner (knight's starting point). We'll create a 2D DP array where dp[i][j] represents the minimum health required to reach the princess when starting at cell (i, j). The main idea is to ensure that at any point, the knight never drops to zero or negative health.
The transition involves ensuring that the knight has enough health to move to one of the neighboring cells (right or down), covering the requirement to sustain the journey until the end.
This solution initializes a DP table with values set to infinity for easier minimum comparisons, except for the 'virtual' edges that allow transitions. Starting from the bottom-right corner, it calculates the health required from the target cell back to the knight's starting point, adjusting the minimum health based on the room's value and ensuring it doesn't fall below 1.
JavaScript
Time Complexity: O(m * n), where m is the number of rows and n the number of columns.
Space Complexity: O(m * n), used by the dp table.
In this approach, we use only a single row (or column) to store intermediate results, thereby reducing space complexity. The idea is based on modifying the DP solution to use space proportional to the minimum dimension of the matrix, proceeding row by row or column by column and updating the required health values as we simulate moving from the goal to the start in the minimal dimension.
In this Java solution, we've reduced space complexity by storing results for each row traversal in a single 1D array. The solution iterates backward through columns while updating each min-health leaving values, ultimately outputting the starting health for the knight accurately.
Time Complexity: O(m * n), where m is the number of rows and n the number of columns.
Space Complexity: O(n), using reduced 1D list for the dp array.
| Approach | Complexity |
|---|---|
| Dynamic Programming Approach | Time Complexity: O(m * n), where m is the number of rows and n the number of columns. |
| Space Optimized Dynamic Programming Approach | Time Complexity: O(m * n), where m is the number of rows and n the number of columns. |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Dynamic Programming (2D DP Table) | O(m*n) | O(m*n) | Best for understanding the full state transition clearly during interviews |
| Space Optimized Dynamic Programming | O(m*n) | O(n) | When memory usage matters or when demonstrating DP state compression |
Dungeon Game | Dynamic programming | Leetcode #174 • Techdose • 45,495 views views
Watch 9 more video solutions →Practice Dungeon Game with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor