forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0174.cpp
More file actions
executable file
·30 lines (26 loc) · 793 Bytes
/
LC0174.cpp
File metadata and controls
executable file
·30 lines (26 loc) · 793 Bytes
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
/*
Problem Statement: https://leetcode.com/problems/dungeon-game/
Time: O(m • n)
Space: O(m • n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dungeon) {
int m, n;
m = dungeon.size();
n = dungeon[0].size();
int dp[m][n];
// initialization
dp[m - 1][n - 1] = min(0, dungeon[m - 1][n - 1]);
for (int i = m - 2; i >= 0; i--)
dp[i][n - 1] = min(0, dungeon[i][n - 1] + dp[i + 1][n - 1]);
for (int i = n - 2; i >= 0; i--)
dp[m - 1][i] = min(0, dungeon[m - 1][i] + dp[m - 1][i + 1]);
// dynamic programming
for (int i = m - 2; i >= 0; i--)
for (int j = n - 2; j >= 0; j--)
dp[i][j] = min(0, dungeon[i][j] + max(dp[i + 1][j], dp[i][j + 1]));
return abs(dp[0][0]) + 1;
}
};