LeetCode 174. Dungeon Game(DP)

topic

Meaning of the questions: Each of the grid has numbers, negative numbers mean that you will be less blood, a positive number means you will increase the blood when your blood is 0 when he died, starting from the upper left corner to the lower right corner, you ask beginning the least amount of blood is. Throughout the process can not have blood is zero.

Solution: can only go down or the right. This directed acyclic graph, eight are dynamic programming. However, if the upper-left corner to start planning, there are many cases to consider. From the lower right corner to start planning before they can.

dp [i] [j] representatives from the i, j to the lower right corner, the minimum number of blood needed.

class Solution {
public:
    int dp[1005][1005];
    int calculateMinimumHP(vector<vector<int>>& dungeon) {
       
        
       for(int i=0;i<dungeon.size();i++)
       {
           for(int j=0;j<dungeon[i].size();j++)
           {
               dp[i][j] = 99999999;
           }
       }
        
       for(int i=dungeon.size()-1;i>=0;i--)
       {
          for(int j=dungeon[i].size()-1;j>=0;j--)
          {
            
              if(i!=dungeon.size()-1)
              {
                  if(dungeon[i][j]<0)
                  {
                      int x = dp[i+1][j] + dungeon[i][j]*-1;
                      if(dp[i+1][j]==0)
                          x ++;
                      dp[i][j] = min(dp[i][j],x);
                      
                  }
                  else
                  {
                      int x = (dp[i+1][j] - dungeon[i][j])<0?0:(dp[i+1][j] - dungeon[i][j]);
                      dp[i][j] = min(dp[i][j],x);
                  }
              }
               
              if(j!=dungeon[i].size()-1)
              {
                  if(dungeon[i][j]<0)
                  {
                      int x = dp[i][j+1] + dungeon[i][j]*-1;
                      if(dp[i][j+1]==0)
                          x++;
                      dp[i][j] = min(dp[i][j],x);
                  
                  }
                  else
                  {
                      int x= (dp[i][j+1] - dungeon[i][j])<0?0:(dp[i][j+1] - dungeon[i][j]);
                      dp[i][j]=min(dp[i][j],x);
                  }
              }
              
              if(j==dungeon[i].size()-1&&i==dungeon.size()-1)
              {
                  if(dungeon[i][j]<0)
                  {
                      dp[i][j]=dungeon[i][j]*-1 +1;
                  }
                  else if(dungeon[i][j]==0)
                  {
                      dp[i][j]=1;
                  }
                  else
                      dp[i][j]=0;
              }
          }
       }
        
          return max(dp[0][0],1);
        
    }
    
  
};

Guess you like

Origin www.cnblogs.com/dacc123/p/12236149.html