Dungeon Game Leetcode Python

The demons had captured the princess (P) 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 (K) was initially positioned in the top-left room and must fight his way through the 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, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0‘s) or contain magic orbs that increase the knight‘s health (positive integers).

In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.


Write a function to determine the knight‘s minimum initial health so that he is able to rescue the princess.

For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.

-2 (K) -3 3
-5 -10 1
10 30 -5 (P)

  • 这道题是二维动态规划问题,关键在于构造转移方程。 首先要求每一步移动过程中knight的hp要大于0,其次要求最小。
  • 所以我们可以构造一个MxN 的矩阵DP,用来记录移动过程。其转移方程为 dp[row][col]=max(1,min(dp[row+1][col],dp[row][col+1])-dungeon[row][col])  空间复杂度和时间复杂度都为 O(mn)
  • This is a 2D dynamic planning problem, we need to make HP greater than 0 in every step. And we greedy search from the bottom.
  • The time and space complexity in this problem are both O(mn)
  • The code is as blow
    class Solution:
        # @param dungeon, a list of lists of integers
        # @return a integer
        def calculateMinimumHP(self, dungeon):
            m=len(dungeon)
            n=len(dungeon[0])
            dp=[[0 for index in range(n)] for index in range(m)]
            dp[m-1][n-1]=max(1,1-dungeon[m-1][n-1])
            for row in reversed(range(m-1)):
                dp[row][n-1]=max(1,dp[row+1][n-1]-dungeon[row][n-1])
            for col in reversed(range(n-1)):
                dp[m-1][col]=max(1,dp[m-1][col+1]-dungeon[m-1][col])
            for row in reversed(range(m-1)):
                for col in reversed(range(n-1)):
                    dp[row][col]=max(1,min(dp[row+1][col],dp[row][col+1])-dungeon[row][col])
            return dp[0][0]

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。