720. Knight in the Dungeon
A knight must cross a dungeon dungeon from the top-left room to the bottom-right room, where the exit is. Each room holds a number: a negative value is damage taken on entering, a positive value is health restored, and zero changes nothing. From a room the knight may only step right or down.
The knight dies as soon as health drops to 0 or below, and this also applies to the first and the last room (the first room's value is applied on arrival at the start). Return the minimum starting health that allows the knight to reach the exit alive along some route.
Aim for time O(rows * cols) and extra space O(cols).
Example 1
- Input:
- dungeon = [[-3,5,-4],[-6,-2,3],[1,-7,-1]]
- Output:
- 4
- Explanation:
With 4 starting health the knight can follow the best route and stay alive in every room; with less no route works.
Example 2
- Input:
- dungeon = [[2,-9],[-5,4]]
- Output:
- 4
- Explanation:
Going down first gives 2, -3, 1, so 4 starting health is enough; going right first would need 8.
Constraints
1 ≤ rows, cols ≤ 300
-1000 ≤ dungeon[r][c] ≤ 1000
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(rows * cols)
- Space
- O(cols)