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 grid representing a dungeon. Each cell contains a positive value (health gain) or negative value (damage). Starting at the top-left, you move only right or down to reach the bottom-right where the princess is located. The challenge is computing the minimum initial health required so the knight never drops to 0 or below at any step.
Approach 1: Dynamic Programming (Bottom-Up) (Time: O(m*n), Space: O(m*n))
The key insight: the minimum health required at a cell depends on the minimum health required for the next step (right or down). Instead of thinking forward from the start, compute the requirement backward from the princess. Create a DP table where dp[i][j] represents the minimum health needed when entering cell (i, j). Start from the bottom-right cell and compute the minimum health needed to survive that cell. For every other cell, choose the cheaper path between moving right or down, then subtract the dungeon value. Ensure the result is at least 1 since health cannot drop to zero. This backward dynamic programming formulation turns a tricky survival constraint into a simple state transition. The approach uses classic dynamic programming over a matrix, iterating through all cells exactly once.
Approach 2: Space Optimized Dynamic Programming (Time: O(m*n), Space: O(n))
The full DP table is not strictly required because each state depends only on the current row and the row below. Replace the 2D table with a 1D array representing the minimum health needed for each column in the next step. Iterate from the bottom row upward and update the array from right to left. At each cell, compute the required health using the minimum between the right move and the downward move already stored in the array. Subtract the dungeon value and clamp the result to at least 1. This keeps the same transition logic but reduces memory from O(m*n) to O(n). Space optimization like this is common in array-based DP problems where only adjacent states are needed.
Recommended for interviews: The bottom-up dynamic programming solution is what interviewers typically expect. It shows you recognize the backward dependency and can define the correct DP state. Mentioning the space-optimized version demonstrates deeper understanding of memory optimization and state compression, which is often discussed as a follow-up.
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.
Python
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.
Java
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.
We define dp[i][j] as the minimum initial value needed from (i, j) to the end point. The value of dp[i][j] can be obtained from dp[i+1][j] and dp[i][j+1], that is:
$
dp[i][j] = max(min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j], 1)
Initially, dp[m][n-1] and dp[m-1][n] are both 1, and the values at other positions are maximum.
The time complexity is O(m times n), and the space complexity is O(m times n). Where m and n$ are the number of rows and columns of the dungeon, respectively.
| 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. |
| Dynamic Programming | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Dynamic Programming (2D Table) | O(m*n) | O(m*n) | Standard interview solution. Clear state definition and easiest to reason about. |
| Space Optimized Dynamic Programming | O(m*n) | O(n) | When memory usage matters or when discussing DP state compression. |
Dungeon Game | Dynamic programming | Leetcode #174 • Techdose • 49,643 views views
Watch 9 more video solutions →Practice Dungeon Game with our built-in code editor and test cases.
Practice on FleetCode