zoukankan      html  css  js  c++  java
  • Dungeon Game 解答

    Question

    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.

    Solution

    这道题一看就知道用DP做。但是如果是从(0,0)开始推到(m - 1, n - 1),对于每个点,我们需要纪录两个值: 1. 走到该点需要的最少血量 2. 该点富余的血量。这样,我们无法得到一个判断标准。

    所以,我们从反方向出发。从(m - 1, n - 1)到(0,0),hp[i][j] 代表从(i,j)走到终点需要的最少血量。如果dungeon[i][j]的值为负,那么进入这个格子之前knight需要有的最小HP是-dungeon[i][j] + min(left, right).如果格子的值非负,那么最小HP需求就是1。

     1 public class Solution {
     2     public int calculateMinimumHP(int[][] dungeon) {
     3         int m = dungeon.length, n = dungeon[0].length;
     4         int[][] hp = new int[m][n];
     5         hp[m - 1][n - 1] = Math.max(-dungeon[m - 1][n - 1] + 1, 1);
     6         for (int i = m - 2; i >= 0; i--) {
     7             hp[i][n - 1] = Math.max(-dungeon[i][n - 1] + hp[i + 1][n - 1], 1);
     8         }
     9         for (int i = n - 2; i >= 0; i--) {
    10             hp[m - 1][i] = Math.max(-dungeon[m - 1][i] + hp[m - 1][i + 1], 1);
    11         }
    12         
    13         for (int i = m - 2; i >= 0; i--) {
    14             for (int j = n - 2; j >= 0; j--) {
    15                 hp[i][j] = Math.max(1, -dungeon[i][j] + Math.min(hp[i + 1][j], hp[i][j + 1]));
    16             }
    17         }
    18         return hp[0][0];
    19     }
    20 }
  • 相关阅读:
    项目开发环境
    angluarjs2入门学习资源
    mosquitto安装和测试
    loj#6031. 「雅礼集训 2017 Day1」字符串(SAM 广义SAM 数据分治)
    loj#6030. 「雅礼集训 2017 Day1」矩阵(贪心 构造)
    loj#6029. 「雅礼集训 2017 Day1」市场(线段树)
    HDU4609 3-idiots(生成函数)
    loj#6436. 「PKUSC2018」神仙的游戏(生成函数)
    BZOJ3028: 食物(生成函数)
    洛谷P4841 城市规划(生成函数 多项式求逆)
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4889357.html
Copyright © 2011-2022 走看看