174. Dungeon Game

class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        if(dungeon.length==0||dungeon[0].length==0)
            return 0;
        int M=dungeon.length;
        int N=dungeon[0].length;
        int[][] dp=new int[M][N];
        for(int i=M-1;i>=0;i--)
            for(int j=N-1;j>=0;j--)
            {
                if(i==M-1&&j==N-1)
                    dp[i][j]=1-dungeon[i][j];
                else if(i==M-1)
                    dp[i][j]=dp[i][j+1]-dungeon[i][j];
                else if(j==N-1)
                    dp[i][j]=dp[i+1][j]-dungeon[i][j];
                else
                    dp[i][j]=Math.min(dp[i+1][j],dp[i][j+1])-dungeon[i][j];
                if(dp[i][j]<=0)
                    dp[i][j]=1;
            }
        return dp[0][0];
    }
}

  

posted @ 2017-10-25 02:55  Weiyu Wang  阅读(86)  评论(0编辑  收藏  举报