Leetcode 174. Dungeon Game

The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.

The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately.

Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0’s) or contain magic orbs that increase the knight’s health (positive integers).

In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
原题连接:https://leetcode.com/problems/dungeon-game/description/

思路:
动态规划。
要求英雄从起点出发最小的血量。
考虑极端情况,只有一个格子。如果格子值val是负数,则英雄血量至少为1-val;如果是整数,则英雄只需要1点血量保证存活即可。
考虑2*2的grid,上面已经算出了到达最后一个格子最少需要的血量,那么结合grid[0][1]和grid[1][0],我们能推出这两个格子至少需要的血量。
grid[0][0]可以从01和10推出。
从上面分析,我们可以用一个二维的life数组表示从当前点走到右下角,英雄在当前点需要的最少血量,最后递推出的life[0][0]即是所求值。

public int calculateMinimumHP(int[][] dungeon) {
    if (dungeon == null || dungeon.length == 0 || dungeon[0].length == 0) {
        return 0;
    }

    int m = dungeon.length, n = dungeon[0].length;
    int[][] life = new int[m][n];
    life[m-1][n-1] = dungeon[m-1][n-1] < 0 ? 1-dungeon[m-1][n-1] : 1;
    for (int i = m-2; i >= 0; i--) {
        life[i][n-1] = dungeon[i][n-1] < life[i+1][n-1] ? life[i+1][n-1] - dungeon[i][n-1] : 1;
    }
    for (int j = n-2; j >= 0; j--) {
        life[m-1][j] = dungeon[m-1][j] < life[m-1][j+1] ? life[m-1][j+1] - dungeon[m-1][j] : 1;
    }

    for (int i = m-2; i >= 0; i--) {
        for (int j = n-2; j >= 0; j--) {
            int next = Math.min(life[i+1][j], life[i][j+1]);
            life[i][j] = dungeon[i][j] < next ? next - dungeon[i][j] : 1;
        }
    }

    return life[0][0];
}
    原文作者:ShutLove
    原文地址: https://www.jianshu.com/p/d0a28b610431
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞