程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> letcode

letcode

編輯:關於C++

 

 

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.

    分析:

    動態規劃的題,時間復雜度和空間復雜度都是O(m*n),其中空間復雜度可以利用滾動數組優化為O(min(m,n));

     

    class Solution {
    public:
        int calculateMinimumHP(vector>& dungeon) {
            if(dungeon.empty() || dungeon[0].empty())
                return -1;
            int rows=dungeon.size(),cols=dungeon[0].size();
            vector> dp(rows,vector(cols,0));
            dp.back().back()=dungeon.back().back()>=0?1:1+(-1)*dungeon.back().back();
            int begini=rows-1,beginj=cols-2;
            if(cols==1)
            {
                if(rows==1)
                    return dp[0][0];
                else
                {
                    begini=rows-2;
                    beginj=0;
                }
            }
            for(int i=begini;i>=0;--i)
            {
                for(int j=i==begini?beginj:cols-1;j>=0;--j)
                {
                    int tmp;
                    if(i

     

     

     

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved