【LeetCode】Dungeon Game 解题报告【Solution】

【题目】

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.

【题意】

有mxn个格子,皇后在右下角,勇士在左上角,现在勇士要去救皇后,每步可以往下或往右走,每个格子里的数字表示勇士到该处时要消耗或增加的魔力,(负数表示消耗,正数表示增加),不论何时只要勇士的魔力小于等于0,勇士立即死掉。问勇士初始至少要有多少魔力?

【解析】

思路:动态规划

用一个二维数组ans[][]表示到每个格子时,勇士到每一步时至少需要的魔力,如ans[i][j]表示勇士在[i, j]处至少需要ans[i][j]魔力才能到达[m, n]救出皇后。

技巧:从[m, n]往回遍历到[1, 1]

动规方程:如果当前位置魔力正且大于等于右边/下边需要的魔力,则该处不需要额外的魔力,否则,勇士到达该处时需有一定的魔力来满足该处和右边/下边需要的魔力。

【Java代码】

public class Solution {
    public int calculateMinimumHP(int[][] dungeon) {
        int m = dungeon.length;
        int n = dungeon[0].length;

        int[][] ans = new int[m][n];

        //初始化最后一行和最后一列
        ans[m - 1][n - 1] = dungeon[m - 1][n - 1] > 0 ? 0 : -dungeon[m - 1][n - 1];
        for (int i = m - 2; i >= 0; i--) {
            ans[i][n - 1] = dungeon[i][n - 1] >= ans[i + 1][n - 1] ? 0 : ans[i + 1][n - 1] - dungeon[i][n - 1];
        }
        for (int j = n - 2; j >= 0; j--) {
            ans[m - 1][j] = dungeon[m - 1][j] >= ans[m - 1][j + 1] ? 0 : ans[m - 1][j + 1] - dungeon[m - 1][j];
        }

        //从右下角往左上角遍历
        for (int i = m - 2; i >= 0; i--) {
            for (int j = n - 2; j >= 0; j--) {
                int down = dungeon[i][j] >= ans[i + 1][j] ? 0 : ans[i + 1][j] - dungeon[i][j];
                int right = dungeon[i][j] >= ans[i][j + 1] ? 0 : ans[i][j + 1] - dungeon[i][j];
                ans[i][j] = Math.min(down, right);
            }
        }

        //要保证勇士活着,至少需要1魔力
        return ans[0][0] + 1;
    }
}
时间: 2024-10-24 12:23:33

【LeetCode】Dungeon Game 解题报告【Solution】的相关文章

LeetCode: Combination Sum 解题报告

Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Question Solution Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The

【LeetCode】Subsets 解题报告

[题目] Given a set of distinct integers, S, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example, If S = [1,2,3], a solution is: [ [3], [1], [2], [1,2,

[LeetCode]LRU Cache, 解题报告

题目 Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

Leetcode:Scramble String 解题报告

Scramble String Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = "great": great / gr eat / \ / g r e at / a t To scramble the string,

LeetCode ZigZag Conversion 解题报告

对输入字符串,做蛇形变化,然后按行输出. https://oj.leetcode.com/problems/zigzag-conversion/ 例如:The string "PAYPALISHIRING"  的蛇形变化如下: P        A           H        N A   P   L    S     I     I   G Y         I            R 最后要求输出的就是:"PAHNAPLSIIGYIR" Write

【原创】leetCodeOj --- Dungeon Game 解题报告

原题地址: https://oj.leetcode.com/problems/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 init

LeetCode: Gas Station 解题报告

Gas Station There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journ

Leetcode:Interleaving String 解题报告

Interleaving StringGiven s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example,Given:s1 = "aabcc",s2 = "dbbca", When s3 = "aadbbcbcac", return true.When s3 = "aadbbbaccc", return false.

LeetCode: Merge Intervals 解题报告

Merge IntervalsGiven a collection of intervals, merge all overlapping intervals. For example,Given [1,3],[2,6],[8,10],[15,18],return [1,6],[8,10],[15,18]. SOLUTION 1: 1. 先使用Comparator 的匿名类对intervels进行排序. 2. 把Intervals遍历一次,依次一个一个merge到第1个interval. 把第1