A knight starts in top-left of a dungeon, must reach bottom-right to save the princess. Each cell adds or subtracts health. Find minimum initial health (at least 1) needed.
Work backwards from bottom-right. dp[i][j] = minimum health needed when entering cell (i,j). dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j]).
- dp[m][n-1] = max(1, 1 - dungeon[m-1][n-1]).
- For i from m-1 to 0, j from n-1 to 0 (excluding bottom-right):
- need = min(right_need, down_need) - dungeon[i][j].
- dp[i][j] = max(1, need).
- Time Complexity: O(M*N)
- Space Complexity: O(M*N)