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) is initially positioned in the top-left, and must fight his, through the dungeon T O rescue the princess.
The knight has an initial health point represented by a positive integer. Drops to 0 or below, he dies immediately.
Some of the rooms is guarded by demons, so the knight loses health (negative integers) upon entering these rooms ; Other rooms is either empty (0 ' s) or contain magic orbs that increase the knight ' s Health (positive int Egers).
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's able to rescue the princess.
For example, given the dungeon below, the initial health of the knight must is at least 7 if he follows the Optim Al path RIGHT-> RIGHT -> DOWN -> DOWN
.
-2 (K) |
-3 |
3 |
-5 |
-10 |
1 |
10 |
30 |
-5 (P) |
- This problem is two-dimensional dynamic programming, the key is the tectonic transfer equation. The first requirement for each step of the move process Knight HP is greater than 0, followed by the minimum requirements.
- So we can construct a matrix DP of MXN to record the moving process. Its transfer equation is Dp[row][col]=max (1,min (dp[row+1][col],dp[row][col+1])-dungeon[row][col]) space complexity and time complexity are O (MN)
- This was 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 is 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]
Dungeon Game Leetcode Python