zoukankan      html  css  js  c++  java
  • [LeetCode] Dungeon Game

    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.

    跟之前的吃豆人一题很像,但是加了一些限制,就是在从左上角到右下角的路径中不能让骑士的血量低于0,所以我们要找的不是走到最后剩余血量最多的那一条路径,而是路径上的最小值最大的那一条。因为路径中还有正数,所以正向处理起来感觉比较麻烦,可以考虑逆向处理,从右下角像左上角处理,dp[i][j]表示从坐标(i, j)到右下角所需的血量。初始化时假设最后剩余血里为0,而

    状态转移方程:

    dungeon[i][j] = max(min(dungeon[i][j+1], dungeon[i+1][j])-dungeon[i][j], 0)
     1 class Solution {
     2 public:
     3     int calculateMinimumHP(vector<vector<int> > &dungeon) {
     4         int m = dungeon.size();
     5         int n = dungeon[0].size();
     6         dungeon[m-1][n-1] = max(0-dungeon[m-1][n-1], 0);
     7         for (int i = m - 2; i >= 0; --i) {
     8             dungeon[i][n-1] = max(dungeon[i+1][n-1]-dungeon[i][n-1], 0);
     9         }
    10         for (int j = n - 2; j >= 0; --j) {
    11             dungeon[m-1][j] = max(dungeon[m-1][j+1]-dungeon[m-1][j], 0);
    12         }
    13         for (int i = m - 2; i >= 0; --i) {
    14             for (int j = n - 2; j >= 0; --j) {
    15                 dungeon[i][j] = max(min(dungeon[i][j+1], dungeon[i+1][j])-dungeon[i][j], 0);
    16             }
    17         }
    18         return dungeon[0][0] + 1;
    19     }
    20 };
  • 相关阅读:
    thinkpa R61i安装XP SATA的解决方法
    成都港宏4S店买的日产,送的无牌DVD 和可视倒车品牌是路特仕 80007
    设计模式之:解剖观察者模式
    java使用siger 获取服务器硬件信息(CPU 内存 网络 io等)
    lephone 壁纸(裸婚时代 童佳倩姚笛壁纸)
    C# 让程序自动以管理员身份运行
    项目管理的5大过程组、9大知识域、44个管理流程的映射关系
    Spring Security 中如何让用户名不存在的错误显示出来(用户名不存在显示Bad credentials)
    eclipse老是报ThreadPoolExecutor$Worker.run()
    Unison文件夹同步工具
  • 原文地址:https://www.cnblogs.com/easonliu/p/4237644.html
Copyright © 2011-2022 走看看