Welcome to Subscribe On Youtube

Question

Formatted question description: https://leetcode.ca/all/174.html

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

Algorithm

Dynamic Programming is used to create a two-dimensional array dp, where dp[i][j] is used to represent the initial HP from the current position (i, j), and the first thing to process is the initial HP of the room where the princess is, and then slowly spread to the first room, continuously getting the best health value in each location. Reverse engineering is the essence of this question.

Formula: dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j])

Code

  • 
    /* test case:
    
    1 (K)	-3	    3
    0	    -2	    0
    -3	    -3	    -3 (P)
    
     */
    
    public class Dungeon_Game {
    
        class Solution {
            public int calculateMinimumHP(int[][] dungeon) {
                if (dungeon == null || dungeon[0].length == 0) {
                    return 0;
                }
    
                int m = dungeon.length;
                int n = dungeon[0].length;
    
                int[][] dp = new int[m][n];
    
                // dp[i][j] is used to indicate the starting HP from the current position (i, j)
                dp[m - 1][n - 1] = Math.max(1, 1 - dungeon[m - 1][n - 1]);
    
                // Initialization the last column
                for (int i = m - 2; i >= 0; i--) {
                    dp[i][n - 1] = Math.max(1, dp[i + 1][n - 1] - dungeon[i][n - 1]);
                }
    
                // Initialization the last row
                for (int i = n - 2; i >= 0; i--) {
                    dp[m - 1][i] = Math.max(1, dp[m - 1][i + 1] - dungeon[m - 1][i]);
                }
    
                for (int i = m - 2; i >= 0; i--) {
                    for (int j = n - 2; j >= 0; j--) {
                        dp[i][j] = Math.max(
                            1,
                            Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]
                        );
                    }
                }
    
                return dp[0][0];
    
            }
        }
    }
    
    ############
    
    class Solution {
        public int calculateMinimumHP(int[][] dungeon) {
            int m = dungeon.length, n = dungeon[0].length;
            int[][] dp = new int[m + 1][n + 1];
            for (var e : dp) {
                Arrays.fill(e, 1 << 30);
            }
            dp[m][n - 1] = dp[m - 1][n] = 1;
            for (int i = m - 1; i >= 0; --i) {
                for (int j = n - 1; j >= 0; --j) {
                    dp[i][j] = Math.max(1, Math.min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
                }
            }
            return dp[0][0];
        }
    }
    
  • // OJ: https://leetcode.com/problems/dungeon-game
    // Time: O(MN)
    // Space: O(1)
    class Solution {
    public:
        int calculateMinimumHP(vector<vector<int>>& A) {
            int M = A.size(), N = A[0].size();
            for (int i = M - 1; i >= 0; --i) {
                for (int j = N - 1; j >= 0; --j) {
                    int need = min(i + 1 < M ? A[i + 1][j] : INT_MAX, j + 1 < N ? A[i][j + 1] : INT_MAX);
                    if (need == INT_MAX) need = 1;
                    A[i][j] = max(1, need - A[i][j]);
                }
            }
            return A[0][0];
        }
    };
    
  • class Solution:
        def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
            m, n = len(dungeon), len(dungeon[0])
            dp = [[inf] * (n + 1) for _ in range(m + 1)]
            dp[m][n - 1] = dp[m - 1][n] = 1
            for i in range(m - 1, -1, -1):
                for j in range(n - 1, -1, -1):
                    dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j])
            return dp[0][0]
    
    ############
    
    class Solution(object):
      def calculateMinimumHP(self, dungeon):
        """
        :type dungeon: List[List[int]]
        :rtype: int
        """
        n = len(dungeon[0])
        need = [2 ** 31] * (n - 1) + [1]
        for row in dungeon[::-1]:
          for j in range(n)[::-1]:
            need[j] = max(min(need[j:j + 2]) - row[j], 1)
        return need[0]
    
    
  • func calculateMinimumHP(dungeon [][]int) int {
    	m, n := len(dungeon), len(dungeon[0])
    	dp := make([][]int, m+1)
    	for i := range dp {
    		dp[i] = make([]int, n+1)
    		for j := range dp[i] {
    			dp[i][j] = 1 << 30
    		}
    	}
    	dp[m][n-1], dp[m-1][n] = 1, 1
    	for i := m - 1; i >= 0; i-- {
    		for j := n - 1; j >= 0; j-- {
    			dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1])-dungeon[i][j])
    		}
    	}
    	return dp[0][0]
    }
    
    func max(a, b int) int {
    	if a > b {
    		return a
    	}
    	return b
    }
    
    func min(a, b int) int {
    	if a < b {
    		return a
    	}
    	return b
    }
    
  • public class Solution {
        public int CalculateMinimumHP(int[][] dungeon) {
            int m = dungeon.Length, n = dungeon[0].Length;
            int[][] dp = new int[m + 1][];
            for (int i = 0; i < m + 1; ++i) {
                dp[i] = new int[n + 1];
                Array.Fill(dp[i], 1 << 30);
            }
            dp[m][n - 1] = dp[m - 1][n] = 1;
            for (int i = m - 1; i >= 0; --i) {
                for (int j = n - 1; j >= 0; --j) {
                    dp[i][j] = Math.Max(1, Math.Min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
                }
            }
            return dp[0][0];
        }
    }
    

All Problems

All Solutions