Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 67504a9

Browse files
committedNov 17, 2024
Time: 0 ms (100%), Space: 11.7 MB (43.35%) - LeetHub
1 parent 9cf356c commit 67504a9

File tree

1 file changed

+25
-22
lines changed

1 file changed

+25
-22
lines changed
 
Lines changed: 25 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,30 @@
1+
#include<bits/stdc++.h>
2+
13
class Solution {
2-
public:
4+
private:
35
int n, m;
4-
int dp[205][205];
5-
6-
int calculateMinimumHP(vector<vector<int>>& matrix) {
7-
n = matrix.size(), m = matrix[0].size();
8-
memset(dp, 0, sizeof dp);
9-
for (int i = n - 1 ; i >= 0 ; --i) {
10-
for (int j = m - 1 ; j >= 0 ; --j) {
11-
if (i == n - 1 && j == m - 1) {
12-
dp[i][j] = min(0, matrix[i][j]);
13-
}
14-
else if (i == n - 1) {
15-
dp[i][j] = min(0, matrix[i][j] + dp[i][j + 1]);
16-
}
17-
else if (j == m - 1) {
18-
dp[i][j] = min(0, matrix[i][j] + dp[i + 1][j]);
19-
}
20-
else {
21-
dp[i][j] = min(0, matrix[i][j] + max(dp[i][j + 1], dp[i + 1][j]));
22-
}
23-
}
6+
int solve(int i, int j, vector<vector<int>>& grid, vector<vector<int>>& dp) {
7+
if (i == n || j == m) {
8+
return INT_MAX;
9+
}
10+
11+
if (i == (n - 1) && j == (m - 1)) {
12+
return grid[i][j] < 0 ? -grid[i][j] + 1 : 1;
13+
}
14+
15+
if (dp[i][j] != -1) {
16+
return dp[i][j];
2417
}
25-
return abs(dp[0][0]) + 1;
18+
19+
int right = solve(i, j + 1, grid, dp);
20+
int down = solve(i + 1, j, grid, dp);
21+
int mn = min(right, down) - grid[i][j];
22+
return dp[i][j] = mn <= 0 ? 1 : mn;
23+
}
24+
public:
25+
int calculateMinimumHP(vector<vector<int>>& grid) {
26+
n = grid.size(), m = grid[0].size();
27+
vector<vector<int>> dp(n, vector<int>(m, -1));
28+
return solve(0, 0, grid, dp);
2629
}
2730
};

0 commit comments

Comments
 (0)
Please sign in to comment.