Taro Logo

Dungeon Game

#1 Most AskedHard
0 views
Topics:
Dynamic Programming

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.length
  • n == dungeon[i].length
  • 1 <= m, n <= 200
  • -1000 <= dungeon[i][j] <= 1000

Solution


Clarifying Questions

When 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:

  1. What are the dimensions of the dungeon grid, and what is the range of possible health values (positive, negative, or zero) in each cell?
  2. Is it guaranteed that a valid path to the princess always exists, or is it possible that the dungeon is inescapable?
  3. Can the knight's health exceed a certain integer limit (like standard 32-bit integer limits) during the journey, or should we assume standard integer types?
  4. If the grid has dimensions of 1x1, should the minimum initial health just depend on the single cell's value, and does it still need to remain strictly above zero?
  5. Are we allowed to modify the input dungeon grid in-place to optimize space complexity, or is it expected to be treated as read-only?

Brute Force Solution

Approach

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:

  1. Begin at the starting room and look at your available choices to move forward.
  2. Pick one of the available paths and physically walk through every room one by one until you either reach the final room or your health drops to zero or below.
  3. Along the way, calculate your health at each step to see if you ever faint from lack of health.
  4. If you successfully reach the end without fainting, calculate the minimum starting health you would have needed at the very beginning to survive that specific journey.
  5. Step backward and try the next possible path choice, repeating the same journey and health check.
  6. Exhaust every single combination of turns and paths through the entire maze.
  7. Compare the required starting health for all the successful journeys and pick the smallest amount as your final answer.

Code Implementation

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)

Big(O) Analysis

Time Complexity
O(2^(m+n)) – In this brute force approach, we explore every single possible path from the top-left to the bottom-right of the dungeon grid. At each room, we make choices to move either right or down, which creates a branching recursive tree of depth roughly equal to the number of rows m plus columns n. Because we can take two directions at almost every step, the total number of paths tested grows exponentially with the dimensions of the grid. This leads to approximately 2 to the power of (m + n) operations, which simplifies to an exponential time complexity of O(2^(m+n)).
Space Complexity
O(r * c) – To determine the minimum starting health efficiently using dynamic programming, we construct an auxiliary two-dimensional table matching the dimensions of the dungeon grid. If we define N as the total number of rooms in the dungeon, or specifically r rows and c columns, this grid stores the required health at each step. Beyond this table, only a few primitive variables are used for iteration, meaning the extra memory usage scales directly with the size of the dungeon grid.

Optimal Solution

Approach

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:

  1. Start at the very last room, which is the princess's location, and figure out the absolute minimum health needed just to step onto that final square and survive.
  2. Look at the rooms immediately to the left and directly above the final room to see what health you would need upon leaving them to safely reach the next step.
  3. Calculate the required health by taking the needed health for the upcoming safe room and subtracting whatever health bonus or penalty the current room provides.
  4. Ensure that the calculated health never drops below a baseline value of one, because running out of health at any point means immediate failure.
  5. Continue moving backward room by room, always choosing the path that requires the least amount of health to proceed safely.
  6. Work your way systematically all the way back to the very first room of the grid.
  7. Once you reach the starting room using this backward calculation, the resulting number tells you the exact minimum health you needed at the very beginning to guarantee a successful journey.

Code Implementation

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]

Big(O) Analysis

Time Complexity
O(m * n) – To solve the dungeon game, we traverse every single room in the two-dimensional grid of size m rows by n columns exactly once in reverse order. For each room, we perform a constant number of operations by looking at the adjacent right and bottom neighbors to determine the minimum required health. Multiplying the number of rows by the number of columns gives approximately m * n operations. Dropping constant factors and simplifying, this results in a final Big O time complexity of O(m * n).
Space Complexity
O(N) – To implement the backward calculation from the final room to the starting room, we allocate an auxiliary 2D DP table (or a optimized 1D array) to store the minimum health required at each step of the grid. If we define N as the number of columns in the grid, a space-optimized approach maintains a single array of size N to keep track of the required health for the current row. As the grid dimensions grow, this temporary array scales linearly with the number of columns, resulting in an auxiliary space complexity of O(N).

Edge Cases

Empty or null dungeon grid input
How to Handle:
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
How to Handle:
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
How to Handle:
Use appropriate integer data types and standard dynamic programming boundary initializations to prevent underflow or overflow.
All cells in the dungeon contain negative values
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
Using the max function against 1 at every step ensures health strictly remains above zero throughout the traversal.
0/4 completed