C++实现LeetCode(174.地牢游戏)

[LeetCode] 174. 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)

Note:

  • 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.

这道王子救公主的题还是蛮新颖的,我最开始的想法是比较右边和下边的数字的大小,去大的那个,但是这个算法对某些情况不成立,比如下面的情况:

1 (K) -3 3
0 -2 0
-3 -3 -3 (P)

如果按我的那种算法走的路径为 1 -> 0 -> -2 -> 0 -> -3, 这样的话骑士的起始血量要为5,而正确的路径应为 1 -> -3 -> 3 -> 0 -> -3, 这样骑士的骑士血量只需为3。无奈只好上网看大神的解法,发现统一都是用动态规划 Dynamic Programming 来做,建立一个二维数组 dp,其中 dp[i][j] 用来表示当前位置 (i, j) 出发的起始血量,最先处理的是公主所在的房间的起始生命值,然后慢慢向第一个房间扩散,不断的得到各个位置的最优的生命值。逆向推正是本题的精髓所在啊,仔细想想也是,如果从起始位置开始遍历,我们并不知道初始时应该初始化的血量,但是到达公主房间后,我们知道血量至少不能小于1,如果公主房间还需要掉血的话,那么掉血后剩1才能保证起始位置的血量最小。那么下面来推导状态转移方程,首先考虑每个位置的血量是由什么决定的,骑士会挂主要是因为去了下一个房间时,掉血量大于本身的血值,而能去的房间只有右边和下边,所以当前位置的血量是由右边和下边房间的可生存血量决定的,进一步来说,应该是由较小的可生存血量决定的,因为较我们需要起始血量尽可能的少,因为我们是逆着往回推,骑士逆向进入房间后 PK 后所剩的血量就是骑士正向进入房间时 pk 前的起始血量。所以用当前房间的右边和下边房间中骑士的较小血量减去当前房间的数字,如果是负数或着0,说明当前房间是正数,这样骑士进入当前房间后的生命值是1就行了,因为不会减血。而如果差是正数的话,当前房间的血量可能是正数也可能是负数,但是骑士进入当前房间后的生命值就一定要是这个差值。所以我们的状态转移方程是 dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j])。为了更好的处理边界情况,我们的二维 dp 数组比原数组的行数列数均多1个,先都初始化为整型数最大值 INT_MAX,由于我们知道到达公主房间后,骑士火拼完的血量至少为1,那么此时公主房间的右边和下边房间里的数字我们就都设置为1,这样到达公主房间的生存血量就是1减去公主房间的数字和1相比较,取较大值,就没有问题了,代码如下:

解法一:

class Solution {
public:
    int calculateMinimumHP(vector<vector<int>>& dungeon) {
        int m = dungeon.size(), n = dungeon[0].size();
        vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MAX));
        dp[m][n - 1] = 1; dp[m - 1][n] = 1;
        for (int i = m - 1; i >= 0; --i) {
            for (int j = n - 1; j >= 0; --j) {
                dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
            }
        }
        return dp[0][0];
    }
};

我们可以对空间进行优化,使用一个一维的 dp 数组,并且不停的覆盖原有的值,参见代码如下:

解法二:

class Solution {
public:
    int calculateMinimumHP(vector<vector<int>>& dungeon) {
        int m = dungeon.size(), n = dungeon[0].size();
        vector<int> dp(n + 1, INT_MAX);
        dp[n - 1] = 1;
        for (int i = m - 1; i >= 0; --i) {
            for (int j = n - 1; j >= 0; --j) {
                dp[j] = max(1, min(dp[j], dp[j + 1]) - dungeon[i][j]);
            }
        }
        return dp[0];
    }
};

到此这篇关于C++实现LeetCode(174.地牢游戏)的文章就介绍到这了,更多相关C++实现地牢游戏内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现LeetCode(63.不同的路径之二)

    [LeetCode] 63. Unique Paths II 不同的路径之二 A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right c

  • C++实现LeetCode(61.旋转链表)

    [LeetCode] 61. Rotate List 旋转链表 Given the head of a linked list, rotate the list to the right by k places. Example 1: Input: head = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3] Example 2: Input: head = [0,1,2], k = 4 Output: [2,0,1] Constraints: The number

  • C++实现LeetCode(64.最小路径和)

    [LeetCode] 64. Minimum Path Sum 最小路径和 Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in t

  • C++实现LeetCode(59.螺旋矩阵之二)

    [LeetCode] 59. Spiral Matrix II 螺旋矩阵之二 Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. Example: Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] 此题跟之前那道 Spiral Matrix 本质上没什么区别,就相当于个类似逆

  • C++实现LeetCode(60.序列排序)

    [LeetCode] 60. Permutation Sequence 序列排序 The set [1,2,3,...,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for n = 3: "123" "132" "213" &

  • C++实现LeetCode(62.不同的路径)

    [LeetCode] 62. Unique Paths 不同的路径 A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner

  • C++实现LeetCode(70.爬楼梯问题)

    [LeetCode] 70. Climbing Stairs 爬楼梯问题 You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Examp

  • C++实现LeetCode(189.旋转数组)

    [LeetCode] 189. Rotate Array 旋转数组 Given an array, rotate the array to the right by k steps, where k is non-negative. Example 1: Input: [1,2,3,4,5,6,7] and k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate

  • C++实现LeetCode(174.地牢游戏)

    [LeetCode] 174. 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 t

  • C++实现LeetCode(55.跳跃游戏)

    [LeetCode] 55. Jump Game 跳跃游戏 Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach th

  • C++实现LeetCode(45.跳跃游戏之二)

    [LeetCode] 45. Jump Game II 跳跃游戏之二 Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last i

  • C++实现LeetCode(312.打气球游戏)

    [LeetCode] 312. Burst Balloons 打气球游戏 Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon iyou will get nums[left] * nums[i]

  • 基于javascript代码检测访问网页的浏览器呈现引擎、平台、Windows操作系统、移动设备和游戏系统

    废话不多说了,直接给大家贴js代码了,代码附有注释,感兴趣的朋友一起学习吧. /** * Author: laixiangran. * Created by laixiangran on 2015/12/02. * 检测访问网页的浏览器呈现引擎.平台.Windows操作系统.移动设备和游戏系统 * ******************************************************************** * 各版本浏览器在windows10.0下的用户代理字符串:

  • js+ajax实现的A*游戏路径算法整理第1/2页

    作者:llinzzi 日期:2007-05-24 去年做了个小东西,一个在线WebGame,目前只实现了多人聊天,移动,拖动画面移动,场景系统等,可以当场景聊天室使用.不过扔了一年了.如图 美工由静电设计后台将由老于开发 今年想再捡起来好好做做,由于是基于坐标点的,所以移动路径非常费资源.找到了一个A*的路径算法,挺智能. 转载一些介绍[转自 http://data.gameres.com/message.asp?TopicID=25439]译者序:很久以前就知道了A*算法,但是从未认真读过相关

  • 使用graphics.py实现2048小游戏

    1.过年的时候在手机上下载了2048玩了几天,心血来潮决定用py写一个,刚开始的时候想用QT实现,发现依赖有点大.正好看到graphics.py是基于tkinter做的封装就拿来练手,并借用了CSDN一位朋友封装的model.py(2048逻辑部分) 2.由于是练手的所以不免有写的不好的地方请大家喷的轻点. 先看看演示图片 附上源码: 2048主程 复制代码 代码如下: #-*-coding:utf-8-*- #python3.3.5 from graphics import* from tki

  • C++实现随机生成迷宫地牢

    可以用这个地图核心做成一个无限迷宫类的游戏 main.cpp // Author: FreeKnight 2014-09-02 #include "stdafx.h" #include <iostream> #include <string> #include <random> #include <cassert> /* 简单逻辑流程描述: 将整个地图填满土 在地图中间挖一个房间出来 选中某一房间(如果有多个的话)的墙壁 确定要修建某种新

  • C++控制台实现随机生成路径迷宫游戏

    本程序是在控制台下随机生成迷宫路径的一个C++程序,可以通过修改宏定义 M 和 N 的值来修改迷宫的长度和宽度,运行程序后 按1开始游戏 按2退出游戏,游戏入口在左上角,出口在右下角,人物(星星)到达右下角出口提示成功闯关. #include<stdio.h> #include<stdlib.h> #include<string.h> #include<conio.h> #include<iostream.h> #include<ctime

  • 迷宫游戏控制台版C++代码

    本文实例分享了C++设计的一个可以调整大小的迷宫游戏,给定迷宫的入口.如果存在出口,程序能够显示行走的路径,并最终到达出口,并输出"成功走出迷宫":如果不存在出口,程序也能够显示行走的过程,并最终回退到入口,并输出"回退到入口". //这是一个迷宫游戏 #include<iostream> #include<ctime> #include<cstdlib>/*用于生成随机数,形成随机变化的迷宫*/ #include<ioma

随机推荐