-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0931_minFallingPathSum.cc
60 lines (55 loc) · 1.19 KB
/
Problem_0931_minFallingPathSum.cc
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
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
int minFallingPathSum(vector<vector<int>> &matrix)
{
int n = matrix.size();
int m = matrix[0].size();
vector<vector<int>> dp(n, vector<int>(m, INT32_MAX));
for (int j = 0; j < m; j++)
{
dp[n - 1][j] = matrix[n - 1][j];
}
for (int i = n - 2; i >= 0; i--)
{
for (int j = n - 1; j >= 0; j--)
{
dp[i][j] = dp[i + 1][j] + matrix[i][j];
if (j - 1 >= 0)
{
dp[i][j] = std::min(dp[i][j], dp[i + 1][j - 1] + matrix[i][j]);
}
if (j + 1 < n)
{
dp[i][j] = std::min(dp[i][j], dp[i + 1][j + 1] + matrix[i][j]);
}
}
}
int ans = INT32_MAX;
for (int j = 0; j < m; j++)
{
ans = std::min(ans, dp[0][j]);
}
return ans;
}
};
void test()
{
Solution s;
vector<vector<int>> m1 = {{2, 1, 3}, {6, 5, 4}, {7, 8, 9}};
vector<vector<int>> m2 = {{-19, 57}, {-40, -5}};
EXPECT_EQ_INT(13, s.minFallingPathSum(m1));
EXPECT_EQ_INT(-59, s.minFallingPathSum(m2));
EXPECT_SUMMARY;
}
int main()
{
test();
return 0;
}