(Hard) Dungeon Game LeetCode

 

Description

Solution

 

class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        
        if(dungeon== null|| dungeon.length ==0||dungeon[0].length==0){
            
            return 0;
        }
        
        //Reverse Dynamic Programming.
        
        // Border Scenario 
        
        //Right-most column
        
        int row = dungeon.length;
        
        int col = dungeon[0].length; 
        
        int [][] dp = new int [row][col];
        
        dp[row-1][col-1] = dungeon[row-1][col-1]>0? 0: -dungeon[row-1][col-1];
        
        for(int i = row-2; i>=0; i-- ){
            
            dp[i][col-1] = Math.max(0, dp[i+1][col-1]-dungeon[i][col-1]);
            
        }
        
        //Down-most row;
        
        for(int j = col-2; j>=0; j--){
            
            dp[row-1][j] = Math.max(0,dp[row-1][j+1] -dungeon[row-1][j] );
        }
        
        
        //middle;
        
        for(int i = row-2; i>=0;i--){
            for(int j= col-2; j>=0; j--){
                
                dp[i][j] = Math.max(0,Math.min(dp[i][j+1],dp[i+1][j]) - dungeon[i][j]);
            }
        }
        
        return dp[0][0]+1;
    }
    
}

 

posted @ 2019-08-05 17:11  CodingYM  阅读(169)  评论(0编辑  收藏  举报