zoukankan      html  css  js  c++  java
  • Dungeon Game 分类: Leetcode 2015-01-15 09:10 69人阅读 评论(0) 收藏

    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.

    这种类型的题目属于迷宫遍历,最容易想到就是动态规划或者深度搜索,这道题目用的是动态规划。动态规划问题实际上是求解一个初始值和递归关系。
    class Solution {
    public:
        int calculateMinimumHP(vector<vector<int> > &dungeon) {
            int m,n,i,j;
            m = dungeon.size();
            n = dungeon[0].size();
            int f[m][n];
            f[m-1][n-1] = max(0-dungeon[m-1][n-1],0); 
            for(i=m-2;i>=0;i--)
            {
                f[i][n-1]= max(-dungeon[i][n-1]+f[i+1][n-1],0);
            }
            for(j=n-2;j>=0;j--)
            {
                f[m-1][j]=max(-dungeon[m-1][j]+f[m-1][j+1],0);
            }
            for(i=m-2;i>=0;i--)
            {
                for(j=n-2;j>=0;j--)
                {
                    f[i][j]= max(min(f[i+1][j]-dungeon[i][j],f[i][j+1]-dungeon[i][j]),0);
                    
                }
            }
            return f[0][0]+1;
        }
    };


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Ubuntu的启动配置文件grub.cfg(menu.lst)设置指南zz
    Qt/E客户端服务期间通信数据串行化
    开源协议简介BSD、 Apache Licence、GPL、LGPL、MIT转载
    Qt/E服务器到客户端的消息传递
    解决 Windows 和 Ubuntu 时间不一致的问题转载
    Qt/E服务器客户端架构
    Qt/E中的键盘设备管理
    Qt/E服务器客户端的通信机制
    解决 ssh 登录慢 转载
    c# 扩展方法奇思妙用变态篇一:由 Fibonacci 数列引出 “委托扩展” 及 “递推递归委托”
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656975.html
Copyright © 2011-2022 走看看