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;
        }
    };


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

  • 相关阅读:
    linux 里 /etc/passwd 、/etc/shadow和/etc/group 文件内容解释
    IIS 7.5 配置 php 5.4.22 链接 sql 2008(用PDO链接数据库)
    如何学好一本编程语言
    从零开始学YII2.0
    android AlertDialog 错误 OnClickListener 报错
    胖哥从零开始做一个APP系列文章的通知
    引用自定义控件出现的问题
    java hashMap实现原理
    粗略读完opengl
    求知若饥,虚心若愚
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656975.html
Copyright © 2011-2022 走看看