dp
with dimensions m x n
, where m
and n
are the number of rows and columns in the dungeon
respectively.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.dp
to handle the boundary conditions.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
.dp[0][0]
as the result.