HardNo. 0174

Dungeon Game — LeetCode 174 Python Solution

Topics
Array, Dynamic Programming, Matrix
Reading time
2 min

The problem

The demons had captured the princess 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.

Example

Input
dungeon = [[-2,-3,3],[-5,-10,1],[10,30,-5]]
Output
7
Explanation
The initial health of the knight must be at least 7 if he follows the optimal path: RIGHT-> RIGHT -> DOWN -> DOWN.

Python solution

PythonSolution
class Solution:
    def calculateMinimumHP(self, dungeon: List[List[int]]) -> int:
        m, n = len(dungeon), len(dungeon[0])
        dp = [[inf] * (n + 1) for _ in range(m + 1)]
        dp[m][n - 1] = dp[m - 1][n] = 1
        for i in range(m - 1, -1, -1):
            for j in range(n - 1, -1, -1):
                dp[i][j] = max(1, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j])
        return dp[0][0]

Complexity

Time
O(m × n)
Space · auxiliary
O(m × n)

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 174. Dungeon Game is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0063Unique Paths IIMedium
0064Minimum Path SumMedium
0085Maximal RectangleHard
0221Maximal SquareMedium
0329Longest Increasing Path in a MatrixHard
054201 MatrixMedium

Frequently asked questions

How hard is LeetCode 174. Dungeon Game?

LeetCode 174. Dungeon Game is rated Hard on LeetCode.

What is the time complexity of LeetCode 174. Dungeon Game?

The Python solution on this page runs in O(m × n).

What is the space complexity of LeetCode 174. Dungeon Game?

The Python solution on this page uses O(m × n) auxiliary space.

What topics does LeetCode 174. Dungeon Game cover?

LeetCode 174. Dungeon Game is tagged Array, Dynamic Programming and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.