My Java Solution


  • 0
    S
    public int calculateMinimumHP(int[][] dungeon) {
            
            if (dungeon.length == 0) {
                return 1;
            }
            
            int [][] life = new int[dungeon.length][dungeon[0].length];
            life[life.length-1][life[0].length-1] = Math.max(1, 1 - dungeon[dungeon.length-1][dungeon[0].length-1]);
            
            for (int i = life.length - 2, j = life[0].length - 1 ; i >= 0; i--) {
                life[i][j] = Math.max(life[i+1][j] - dungeon[i][j], 1);
            }
            
            for (int i = life.length - 1, j = life[0].length - 2 ; j >= 0; j--) {
                life[i][j] = Math.max(life[i][j+1] - dungeon[i][j], 1);
            }
            
            for (int i = dungeon.length - 2; i >= 0; i--) {
                for (int j = dungeon[0].length - 2; j >=0; j--) {
                    int result1 = Math.max(life[i][j+1] - dungeon[i][j], 1);
                    int result2 = Math.max(life[i+1][j] - dungeon[i][j], 1);
                    life[i][j] = Math.min(result1, result2);
                }
            }
            
            return life[0][0]; 
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.