Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- void getMinFallingSum(int row, int col, int sum, int &minSum, vector<vector<int> > &v){
- if(row >= v.size()){
- if(col < 0 || col >= v[0].size()){
- minSum = min(minSum, sum);
- }
- return;
- }
- if(col < 0 || col >= v[0].size()){
- return;
- }
- //levels - each cell
- //options - bottom left, bottom, bottom right
- sum += v[row][col];
- getMinFallingSum(row + 1, col - 1, sum, minSum, v);
- getMinFallingSum(row + 1, col, sum, minSum, v);
- getMinFallingSum(row + 1, col + 1, sum, minSum, v);
- }
- int getMinFallingSumMemo(int row, int col, vector<vector<int> > &v, vector<vector<int> > &memo){
- if(row == v.size() - 1 && (col >= 0 && col < v[0].size())){
- return v[row][col];
- }
- if(memo[row][col] != INT_MAX){
- return memo[row][col];
- }
- int bottomLeft = INT_MAX, bottom = INT_MAX, bottomRight = INT_MAX;
- if(row < v.size() - 1 && col > 0){
- bottomLeft = getMinFallingSumMemo(row + 1, col - 1, v, memo);
- }
- if(row < v.size() - 1){
- bottom = getMinFallingSumMemo(row + 1, col, v, memo);
- }
- if(row < v.size() - 1 && col < v[0].size() - 1){
- bottomRight = getMinFallingSumMemo(row + 1, col + 1, v, memo);
- }
- return memo[row][col] = v[row][col] + min(bottomLeft, min(bottom, bottomRight));
- }
- int getMinFallingSumDP(vector<vector<int> > &v){
- int n = v.size(), m = v[0].size();
- vector<vector<int> > dp(n, vector<int>(m, INT_MAX));
- for(int j = 0; j < m; j++){
- dp[n - 1][j] = v[n - 1][j];
- }
- int minFallingSum = INT_MAX;
- for(int i = n - 2; i >= 0; i--){
- for(int j = 0; j < m; j++){
- int bottomLeft = 0, bottom = 0, bottomRight = 0;
- if(j == 0){
- dp[i][j] = min(dp[i + 1][j], dp[i + 1][j + 1]);
- }
- else if(j == m - 1){
- dp[i][j] = min(dp[i + 1][j - 1], dp[i + 1][j]);
- }
- else{
- dp[i][j] = min(dp[i + 1][j - 1], min(dp[i + 1][j], dp[i + 1][j + 1]));
- }
- dp[i][j] += v[i][j];
- if(i == 0){
- minFallingSum = min(minFallingSum, dp[i][j]);
- }
- }
- }
- return minFallingSum;
- }
- int main() {
- // your code goes here
- int n, m;
- cin >> n >> m;
- vector<vector<int> > v(n, vector<int>(m));
- for(int i = 0; i < n; i++){
- for(int j = 0; j < m; j++){
- cin >> v[i][j];
- }
- }
- /*
- //Recursive Call
- int minSum = INT_MAX;
- for(int j = 0; j < m; j++){
- getMinFallingSum(0, j, 0, minSum, v);
- }
- cout << minSum << '\n';
- */
- /*
- //Memo Call
- int minSum = INT_MAX;
- vector<vector<int> > memo(n, vector<int>(m , INT_MAX));
- for(int j = 0; j < m; j++){
- minSum = min(minSum, getMinFallingSumMemo(0, j, v, memo));
- }
- cout << minSum << '\n';
- */
- //DP Call
- cout << getMinFallingSumDP(v) << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement