Dungeon Game — LeetCode 174 Python Solution
HardArrayDynamic ProgrammingMatrix
- Problem
- #174
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(m \times n) auxiliary |
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
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 \times n).
- What is the space complexity of LeetCode 174. Dungeon Game?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 174. Dungeon Game cover?
- LeetCode 174. Dungeon Game is tagged Array, Dynamic Programming and Matrix on LeetCode.