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] <= 1000When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are navigating a maze of rooms where some rooms give you magic health and others drain your health, and you need to reach the very end safely. The brute force approach involves trying every single possible path through the maze from the starting point to the destination.
Here's how the algorithm would work step-by-step:
def calculate_minimum_hp(dungeon_grid):
row_count = len(dungeon_grid)
column_count = len(dungeon_grid[0])
def explore_paths(current_row, current_column):
# We must stop exploring when we step outside the dungeon boundaries
if current_row >= row_count or current_column >= column_count:
return float('inf')
# We calculate the exact health needed upon arrival at the destination room
if current_row == row_count - 1 and current_column == column_count - 1:
room_value = dungeon_grid[current_row][current_column]
return 1 if room_value >= 0 else 1 - room_value
health_via_right = explore_paths(current_row, current_column + 1)
health_via_down = explore_paths(current_row + 1, current_column)
# We select the path requiring less health while ensuring we survive this room
minimum_future_health = min(health_via_right, health_via_down)
current_room_value = dungeon_grid[current_row][current_column]
# We ensure our health never drops to zero or below at any point
if minimum_future_health <= current_room_value:
return 1
else:
return minimum_future_health - current_room_value
return explore_paths(0, 0)To survive the journey to the end, the optimal strategy works backward from the final destination rather than forward from the start. By calculating the minimum health needed at each step in reverse, we can always make the safest choice at every single room.
Here's how the algorithm would work step-by-step:
class Solution:
def calculateMinimumHP(self, dungeon_grid: list[list[int]]) -> int:
row_count = len(dungeon_grid)
col_count = len(dungeon_grid[0])
health_table = [[float('inf')] * (col_count + 1) for _ in range(row_count + 1)]
health_table[row_count][col_count - 1] = 1
health_table[row_count - 1][col_count] = 1
# Working backward ensures we always know the exact minimum health required for the next safe step.
for current_row in range(row_count - 1, -1, -1):
for current_col in range(col_count - 1, -1, -1):
minimum_health_needed = min(
health_table[current_row + 1][current_col],
health_table[current_row][current_col + 1]
) - dungeon_grid[current_row][current_col]
# Health must never drop below one to avoid instant death at any point on the board.
if minimum_health_needed <= 0:
health_table[current_row][current_col] = 1
else:
health_table[current_row][current_col] = minimum_health_needed
# Reaching the start room gives the absolute minimum starting health needed for success.
return health_table[0][0]| Case | How to Handle |
|---|---|
| Empty or null dungeon grid input | Check for null or empty arrays at the start and return zero or raise an exception depending on the strict API contract. |
| Minimum-sized 1x1 dungeon grid | Return either 1 if the single cell is positive or 1 minus the cell value if it is zero or negative. |
| Dungeon cells containing extremely large positive or negative integers | Use appropriate integer data types and standard dynamic programming boundary initializations to prevent underflow or overflow. |
| All cells in the dungeon contain negative values | The bottom-up dynamic programming approach correctly accumulates the debt backwards to determine the necessary starting health. |
| All cells in the dungeon contain positive values | The algorithm correctly reduces the required health requirement down to the baseline minimum of 1 at the start. |
| Grid dimensions are heavily skewed such as 1xN or Nx1 | Iterating through the single row or column bounds without nested loops ensures the logic handles linear paths gracefully. |
| Maximum-sized dungeon grid constraints up to the problem limits | A bottom-up dynamic programming approach with O(n) or O(m times n) space complexity executes efficiently within time limits. |
| Health dropping to zero or below at intermediate cells | Using the max function against 1 at every step ensures health strictly remains above zero throughout the traversal. |