Dungeon Game

来源:互联网 发布:税收数据 编辑:程序博客网 时间:2024/05/17 04:36

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)-33-5-1011030-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.

Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

由于最终目标是骑士到达公主位置,因此在右下角必须满足HP剩余1.

从右下角位置开始倒推,每个位置需要同时满足两个条件:(1)该位置HP为1(保证不死),(2)该位置的HP足够到达公主(使用动态规划)

class Solution {public:    int calculateMinimumHP(vector<vector<int>>& dungeon) {        if(dungeon.size()==0)            return 1;        int rows=dungeon.size();        int cols=dungeon[0].size();                vector<int> cur(cols);        cur[cols-1]=max(1, 1-dungeon[rows-1][cols-1]);                //计算最后一行到达终点所需要的最少点数        for(int i=cols-2; i>=0; i--){            cur[i]=max(1, cur[i+1]-dungeon[rows-1][i]);        }                for(int i=rows-2; i>=0; i--){            cur[cols-1]=max(1, cur[cols-1]-dungeon[i][cols-1]);//计算该行最后一个点到达终点的最低花费点数            for(int j=cols-2; j>=0; j--){                cur[j]=max(1, min(cur[j+1], cur[j])-dungeon[i][j]);//计算从i,j位置到达终点的最低花费点数            }        }                return cur[0];    }};







0 0
原创粉丝点击