bugfree Icon
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course
interview-course

Leetcode Problem 174. Dungeon Game

174. Dungeon Game

Leetcode Solutions

Dynamic Programming Approach

  1. Initialize a 2D array dp with dimensions m x n, where m and n are the number of rows and columns in the dungeon respectively.
  2. Set dp[m-1][n-1] to max(1, 1 - dungeon[m-1][n-1]) to ensure the knight has at least 1 health after the last cell.
  3. Initialize the last row and last column of dp to handle the boundary conditions.
  4. Iterate from m-2 to 0 for rows and from n-2 to 0 for columns: a. Calculate the minimum health required after moving rightward: right_health = max(1, dp[i][j+1] - dungeon[i][j]). b. Calculate the minimum health required after moving downward: down_health = max(1, dp[i+1][j] - dungeon[i][j]). c. Set dp[i][j] to the minimum of right_health and down_health.
  5. Return dp[0][0] as the result.
UML Thumbnail

Backtracking with Memoization

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...