Leetcode Dungeon Game Java

来源:互联网 发布:通联支付 网络是 编辑:程序博客网 时间:2024/05/21 02:33

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.

Write a function to determine the knight’s minimum initial health so that he is able to rescue the princess.

For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.

-2 (K) -3 3
-5 -10 1
10 30 -5 (P)

Notes:

The knight’s health has no upper bound.
Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.

首先,解释一下这道题的题意:dungeon的意思是地牢的意思。首先有一个很坏的恶魔,抓走了我们美丽的公主,然后又有一个抠脚骑士,不对,勇敢的,要去救公主。公主被囚禁在地牢的右下角,骑士只能从地牢左上角进入,并且只能一路向下或者向右(愚蠢的骑士)。给定的二维数组表示地牢,相应的数字表示骑士掉血或者回血的数目。求骑士进入时的最低血量。注:骑士的血量必须一直>0,否则就真抠脚了。

这道题第一想法,使用一个等大的标记数组,标记骑士到该点的需要的最小血量。从前往后,貌似不是一个很好的选择,所以选择了从后往前,即从右下角向左上角标记

程序如下:

    public int calculateMinimumHP(int[][] dungeon) {        if(dungeon==null||dungeon.length==0||dungeon[0].length==0)            return 0;        int row=dungeon.length-1;        int col=dungeon[0].length-1;        int[][] mark=new int[row+1][col+1];        for(int i=row;i>=0;i--){            for(int j=col;j>=0;j--){                if(i==row&&j==col){                    mark[i][j]=dungeon[i][j]<0?(-dungeon[i][j]):0;                }else if(i==row){                    mark[i][j]=(mark[i][j+1]-dungeon[i][j])>0?(mark[i][j+1]-dungeon[i][j]):0;                }else if(j==col){                    mark[i][j]=(mark[i+1][j]-dungeon[i][j])>0?(mark[i+1][j]-dungeon[i][j]):0;                }else {                    mark[i][j]=Math.min((mark[i][j+1]-dungeon[i][j])>0?(mark[i][j+1]-dungeon[i][j]):0, (mark[i+1][j]-dungeon[i][j])>0?(mark[i+1][j]-dungeon[i][j]):0);                }            }        }        return mark[0][0]+1;    }
0 0
原创粉丝点击