-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
90 lines (77 loc) · 2.52 KB
/
Copy pathsolution.cpp
File metadata and controls
90 lines (77 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* Problem: 174. Dungeon Game
* Difficulty: Hard
* Topics: Array, Dynamic Programming, Matrix
* LeetCode Link: https://leetcode.com/problems/dungeon-game/
*
* Time Complexity: O(M * N)
* Space Complexity: O(N) auxiliary space (using 1D rolling array)
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <cassert>
using namespace std;
class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dungeon) {
int m = static_cast<int>(dungeon.size());
int n = static_cast<int>(dungeon[0].size());
// dp[j] represents the minimum HP required before entering cell (i, j)
// Initialize with INT_MAX to safely handle boundary transitions
vector<int> dp(n + 1, INT_MAX);
// Base case: to survive after rescuing the princess at (m-1, n-1),
// we need at least 1 HP upon exiting
dp[n - 1] = 1;
for (int i = m - 1; i >= 0; --i) {
for (int j = n - 1; j >= 0; --j) {
if (i == m - 1 && j == n - 1) {
dp[j] = max(1, 1 - dungeon[i][j]);
} else {
int minExitHP = min(dp[j], dp[j + 1]);
dp[j] = max(1, minExitHP - dungeon[i][j]);
}
}
}
return dp[0];
}
};
// ==========================================
// Local Test Runner (Guarded for LeetCode Submission)
// ==========================================
#ifdef LOCAL_TEST
int main() {
Solution solver;
// Test Case 1: [[-2,-3,3],[-5,-10,1],[10,30,-5]] -> 7
{
vector<vector<int>> dungeon = {
{-2, -3, 3},
{-5, -10, 1},
{10, 30, -5}
};
assert(solver.calculateMinimumHP(dungeon) == 7);
cout << "Test 1 Passed: 3x3 Dungeon -> 7" << endl;
}
// Test Case 2: [[0]] -> 1
{
vector<vector<int>> dungeon = {{0}};
assert(solver.calculateMinimumHP(dungeon) == 1);
cout << "Test 2 Passed: Single neutral cell -> 1" << endl;
}
// Test Case 3: [[100]] -> 1
{
vector<vector<int>> dungeon = {{100}};
assert(solver.calculateMinimumHP(dungeon) == 1);
cout << "Test 3 Passed: Single positive cell -> 1" << endl;
}
// Test Case 4: [[-100]] -> 101
{
vector<vector<int>> dungeon = {{-100}};
assert(solver.calculateMinimumHP(dungeon) == 101);
cout << "Test 4 Passed: Single negative cell -> 101" << endl;
}
cout << "All test cases passed successfully!" << endl;
return 0;
}
#endif