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


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

  • 相关阅读:
    CF1153C. Serval and Parenthesis Sequence
    LGOJ P2048 [NOI2010]超级钢琴
    BZOJ4551: [Tjoi2016&Heoi2016]树
    性能分析 | Java进程CPU占用高导致的网页请求超时的故障排查
    SQL优化 | sql执行过长的时间,如何优化?
    性能优化 | JVM性能调优篇——来自阿里P7的经验总结
    性能优化 | 线上百万级数据查询接口优化过程
    性能分析 | 线上CPU100%排查
    性能测试 | Web端性能测试
    自动化测试 | 好用的自动化测试工具Top 10
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656975.html
Copyright © 2011-2022 走看看