【leetcode dp】Dungeon Game

https://leetcode.com/problems/dungeon-game/description/

【Title】

Given a m*n dungeon, the initial position of the prince is in the upper left corner, and the princess in the lower right corner does not move. The prince is going to save the princess, and each step can only go one square to the right or down. Each grid is an integer. Negative numbers represent health minus corresponding points, and positive numbers represent health increases by corresponding points. It is necessary to ensure that the prince does not hang up in the process of walking, that is, the health after passing through each grid is greater than or equal to 1 , ask the prince what is the initial minimum life value.

【Thinking】

Push dp backwards and calculate the survivable blood volume of (i,j)->(m,n).

dp[i][j]=max(1,min(dp[i+1][j],dp[i][j+1])-a[i][j]]);

【AC】

 1 class Solution {
 2 public:
 3     int calculateMinimumHP(vector<vector<int>>& dungeon) {
 4         int m=dungeon.size();
 5         int n=dungeon[0].size();
 6         const int inf=0x3f3f3f3f;
 7         vector<vector<int> > dp(m+1,vector<int>(n+1));
 8         for(int i=0;i<=m;i++){
 9             for(int j=0;j<=n;j++){
10                 dp[i][j]=inf;
11             }
12         }
13         dp[m-1][n-1]=max(1,1-dungeon[m-1][n-1]);
14         for(int k=m+n-3;k>=0;k--){
15             for(int i=0;i<m;i++){
16                 int j=k-i;
17                 if(j<0||j>=n) continue;
18                 dp[i][j]=max(1,min(dp[i][j+1],dp[i+1][j])-dungeon[i][j]);
19             }
20         }
21         return dp[0][0];
22     }
23 };
View Code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325303311&siteId=291194637