-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_931_MinFallingPathSum.cpp
101 lines (80 loc) · 2.66 KB
/
LC_931_MinFallingPathSum.cpp
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
91
92
93
94
95
96
97
98
99
100
101
/*
https://leetcode.com/problems/minimum-falling-path-sum/
931. Minimum Falling Path Sum
*/
class Solution {
public:
int rows, cols;
vector<vector<int>> dp;
int minFallingPathSum(vector<vector<int>>& matrix) {
rows = matrix.size();
cols = matrix[0].size();
int minPath = INT_MAX;
// dp.resize(rows+1, vector<int>(cols+1, -1));
// for(int c=0; c<cols; c++)
// {
// // minPath = min(minPath, TopToBottom(0, c, matrix));
// minPath = min(minPath, BottomToTop(rows-1, c, matrix));
// }
// With Extra Space
dp.resize(rows, vector<int>(cols, -1));
// From first row to last
for(int c=0; c<cols; c++)
{
dp[0][c]=matrix[0][c];
}
for(int r=1; r<rows; r++)
{
for(int c=0; c<cols; c++)
{
int leftUpDig = ((c==0) ? INT_MAX : dp[r-1][c-1]);
int up = dp[r-1][c];
int rightUpDig = ((c==cols-1) ? INT_MAX: dp[r-1][c+1]);
dp[r][c] = matrix[r][c]+min({leftUpDig, up, rightUpDig});
// if(r==rows-1) // last row
// minPath = min(minPath, dp[r][c]);
}
}
for(int c=0; c<cols; c++)
{
if(dp[rows-1][c] < minPath)
minPath = dp[rows-1][c];
}
// for(int r=0; r<rows; r++)
// {for(int c=0; c<cols; c++)
// {
// cout<<dp[r][c]<<" ";
// }
// cout<<"\n";
// }
return minPath;
}// end
int BottomToTop(int r, int c, vector<vector<int>>& M)
{
if(c<0 || c>=cols)
return INT_MAX;
if(r == 0)
return dp[r][c]=M[r][c];
if(dp[r][c] != -1)
return dp[r][c];
int leftUpDig = BottomToTop(r-1, c-1, M);
int up = BottomToTop(r-1, c, M);
int rightUpDig = BottomToTop(r-1, c+1, M);
return dp[r][c] = M[r][c]+ min({leftUpDig, up, rightUpDig});
// return dp[r][c];
}
int TopToBottom(int r, int c, vector<vector<int>>& M)
{
if(c<0 || c>=cols)
return INT_MAX;
if(r == rows-1)
return M[r][c];
if(dp[r][c] != -1)
return dp[r][c];
int leftDig = TopToBottom(r+1, c-1, M);
int down = TopToBottom(r+1, c, M);
int rightDig = TopToBottom(r+1, c+1, M);
dp[r][c] = M[r][c]+ min({leftDig, down, rightDig});
return dp[r][c];
}
};