Dungeon Game Leetcode Python

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)
  • 这道题是二维动态规划问题,关键在于构造转移方程。 首先要求每一步移动过程中knight的hp要大于0,其次要求最小。
  • 所以我们可以构造一个MxN 的矩阵DP,用来记录移动过程。其转移方程为 dp[row][col]=max(1,min(dp[row+1][col],dp[row][col+1])-dungeon[row][col])  空间复杂度和时间复杂度都为 O(mn)
  • This is a 2D dynamic planning problem, we need to make HP greater than 0 in every step. And we greedy search from the bottom.
  • The time and space complexity in this problem are both O(mn)
  • The code is as blow
    class Solution:
        # @param dungeon, a list of lists of integers
        # @return a integer
        def calculateMinimumHP(self, dungeon):
            m=len(dungeon)
            n=len(dungeon[0])
            dp=[[0 for index in range(n)] for index in range(m)]
            dp[m-1][n-1]=max(1,1-dungeon[m-1][n-1])
            for row in reversed(range(m-1)):
                dp[row][n-1]=max(1,dp[row+1][n-1]-dungeon[row][n-1])
            for col in reversed(range(n-1)):
                dp[m-1][col]=max(1,dp[m-1][col+1]-dungeon[m-1][col])
            for row in reversed(range(m-1)):
                for col in reversed(range(n-1)):
                    dp[row][col]=max(1,min(dp[row+1][col],dp[row][col+1])-dungeon[row][col])
            return dp[0][0]
时间: 2024-11-09 17:00:20

Dungeon Game Leetcode Python的相关文章

[Leetcode]@python 62. Unique Paths

题目链接:https://leetcode.com/problems/unique-paths/ 题目大意:给定n.m,在mxn的矩阵中,从(0,0)走到(m-1,n-1)一共有多少种法(只能往下和往右走) 解题思路:从(0,0)到(m-1,n-1)一共要走m - 1次向下,n-1次向右.也就是在n + m - 2次中选出m-1次向下,也就是C(m + n - 2,m-1) class Solution(object): def uniquePaths(self, m, n): ""&

Pascal's triangle II Leetcode Python

Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? 这题和前面一题的区别在于不用返回所有解,只需要返回index对应行就行.做法和前面的一样定义一个currow 和prerow class Solu

LeetCode Python 位操作 1

Python 位操作: 按位与 &, 按位或 | 体会不到 按位异或 ^ num ^ num = 0 左移 << num << 1 == num * 2**1 右移 >> num >> 2 == num / 2**2 取反 ~ ~num == -(num + 1) 1. Single Number Given an array of integers, every element appears twice except for one. Find

[Leetcode][Python]52: N-Queens II

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 52: N-Queens IIhttps://oj.leetcode.com/problems/n-queens-ii/ Follow up for N-Queens problem.Now, instead outputting board configurations, return the total number of distinct solutions. ===Comm

[Leetcode][Python]41: First Missing Positive

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 41: First Missing Positivehttps://oj.leetcode.com/problems/first-missing-positive/ Given an unsorted integer array, find the first missing positive integer.For example,Given [1,2,0] return 3,a

[LeetCode][Python]Intersection of Two Arrays II

Intersection of Two Arrays II Given two arrays, write a function to compute their intersection. Example:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. Note: Each element in the result should appear as many times as it shows in both arrays

[Leetcode][Python]54: Spiral Matrix

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 54: Spiral Matrixhttps://leetcode.com/problems/spiral-matrix/ Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.For example,Given the foll

[Leetcode][Python]39: Combination Sum

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 39: Combination Sumhttps://oj.leetcode.com/problems/combination-sum/ Given a set of candidate numbers (C) and a target number (T),find all unique combinations in C where the candidate numbers

[Leetcode][Python]40: Combination Sum II

# -*- coding: utf8 -*-'''__author__ = '[email protected]' 40: Combination Sum IIhttps://oj.leetcode.com/problems/combination-sum-ii/ Given a collection of candidate numbers (C) and a target number (T),find all unique combinations in C where the candi