Dungeon Game LeetCode Solution

Last updated on March 1st, 2025 at 10:30 pm

Here, we see a Dungeon Game LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Binary Search, Dynamic Programming

Companies

Microsoft

Level of Question

Hard

Dungeon Game LeetCode Solution

Dungeon Game LeetCode Solution

1. Problem Statement

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:

dungeon grid 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

2. Coding Pattern Used in Solution

The coding pattern used in all the provided implementations is “Dynamic Programming”. Specifically, this problem is a variation of the “0/1 Knapsack” pattern, where we are trying to calculate the minimum health required to survive while traversing a grid. The solution involves breaking the problem into smaller subproblems, solving them recursively or iteratively, and storing intermediate results to avoid redundant calculations.

3. Code Implementation in Different Languages

3.1 Dungeon Game C++

class Solution {
public:
    int calculateMinimumHP(vector<vector<int>>& dungeon) {
        int n = dungeon.size(), m = dungeon[0].size();
        vector<vector<int>> memo(n, vector<int>(m, 1e9));
        memo[n - 1][m - 1] = dungeon[n - 1][m - 1] < 0 ? -dungeon[n - 1][m - 1] + 1 : 1;
        for(int i = n - 1; i >= 0; i--){
            for(int j = m - 1; j >= 0; j--){
                if(i < n - 1)
                    memo[i][j] = min(memo[i][j], max(1, memo[i + 1][j] - dungeon[i][j]));
                if(j < m - 1)
                    memo[i][j] = min(memo[i][j], max(1, memo[i][j + 1] - dungeon[i][j]));
            }
        }
        return memo[0][0];
    }
};

3.2 Dungeon Game Java

class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        int ans = calculateMinimumHP(dungeon,0,0);
        if(ans==0 && dungeon[0][0]<0) ans=dungeon[0][0];
        return ans>=0?1:-1*ans+1;
    }
    public int calculateMinimumHP(int[][] dungeon , int i, int j) {
        if(i==dungeon.length-1 && j==dungeon[0].length-1){
            return dungeon[i][j]>=0?0:dungeon[i][j];
        }
        if(i>=dungeon.length || j>=dungeon[0].length){
            return Integer.MIN_VALUE;
        }
        int bottom =  calculateMinimumHP(dungeon, i+1,j);
        int right = calculateMinimumHP(dungeon, i,j+1);
        int val=dungeon[i][j] + Math.max(bottom,right);
        return val>0?0:val;
    }
}

3.3 Dungeon Game JavaScript

var calculateMinimumHP = function(dungeon) {
    const n = dungeon.length;
    const m = dungeon[0].length;
    const dp = new Array(n).fill(0).map(() => new Array(m).fill(0));
    return helper(dungeon, n, m, 0, 0, dp);
};

var helper = function(dungeon, n, m, row, col, dp) {
    if (row === n - 1 && col === m - 1) {
        return Math.max(1, 1 - dungeon[row][col]);
    }
    if (row >= n || col >= m) {
        return Infinity;
    }
    if (dp[row][col] !== 0) {
        return dp[row][col];
    }
    const right = helper(dungeon, n, m, row, col + 1, dp);
    const down = helper(dungeon, n, m, row + 1, col, dp);
    dp[row][col] = Math.max(1, Math.min(right, down) - dungeon[row][col]);
    return dp[row][col];
};

3.4 Dungeon Game Python

class Solution(object):
    def calculateMinimumHP(self, dungeon):
        n = len(dungeon)
        m = len(dungeon[0])
        dp = [[0] * m for _ in range(n)]
        return self.helper(dungeon, n, m, 0, 0, dp)

    def helper(self, dungeon, n, m, row, col, dp):
        if row == n - 1 and col == m - 1:
            return max(1, 1 - dungeon[row][col])
        if row >= n or col >= m:
            return float('inf')
        if dp[row][col] != 0:
            return dp[row][col]
        right = self.helper(dungeon, n, m, row, col + 1, dp)
        down = self.helper(dungeon, n, m, row + 1, col, dp)
        dp[row][col] = max(1, min(right, down) - dungeon[row][col])
        return dp[row][col]   

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n * m)O(n * m)
JavaO(2n + m)O(n + m)
JavaScriptO(n * m)O(n * m)
PythonO(n * m)O(n * m)
  • The C++ implementation is the most efficient in terms of recursion overhead due to its bottom-up approach.
  • The Java implementation is the least efficient due to the lack of memoization.
  • The JavaScript and Python implementations are efficient and use memoization to optimize the recursive solution.
Scroll to Top