LeetCode 174: Dungeon Game Solution

Master LeetCode problem 174 (Dungeon Game), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

174. Dungeon Game

Problem Explanation

Explanation:

To solve this problem, we can use dynamic programming. We start from the bottom-right corner (princess room) and move towards the top-left corner (knight's starting point). At each cell, we calculate the minimum health needed to reach the princess. We iterate in reverse order to consider the minimum health required to reach the princess from either the cell below or the cell to the right.

We maintain a 2D DP array where dp[i][j] represents the minimum health needed at cell (i, j) to reach the princess. We initialize the last cell (princess room) as max(1, 1-dungeon[m-1][n-1]) since the knight needs at least 1 health point to survive.

Then, we iterate from m-1 to 0 and from n-1 to 0, updating the dp values based on the minimum health required from the cell below or the cell to the right.

Finally, we return the dp[0][0] which represents the minimum initial health needed at the knight's starting point.

  • Time complexity: O(m*n) where m and n are the dimensions of the dungeon.
  • Space complexity: O(m*n) for the DP array.

:

Solution Code

class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        int m = dungeon.length;
        int n = dungeon[0].length;
        
        int[][] dp = new int[m][n];
        
        dp[m-1][n-1] = Math.max(1, 1 - dungeon[m-1][n-1]);
        
        for (int i = m - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                if (i == m - 1 && j == n - 1) continue;
                
                int right = (j == n - 1) ? Integer.MAX_VALUE : dp[i][j+1];
                int down = (i == m - 1) ? Integer.MAX_VALUE : dp[i+1][j];
                
                int minHealth = Math.min(right, down) - dungeon[i][j];
                dp[i][j] = Math.max(1, minHealth);
            }
        }
        
        return dp[0][0];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 174 (Dungeon Game)?

This page provides optimized solutions for LeetCode problem 174 (Dungeon Game) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 174 (Dungeon Game)?

The time complexity for LeetCode 174 (Dungeon Game) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 174 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 174 in Java, C++, or Python.

Back to LeetCode Solutions