Was it helpful?

Question


In this tutorial, we will be discussing a program to find maximum path sum that starting with any cell of 0-th row and ending with any cell of (N-1)-th row

For this we will be provided with a matrix with possible moves of (i+1, j), (i+1, j-1), (i+1, j+1). Our task is to start from zeroth position and move to last row finding out the maximum sum path.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
#define N 4
//finding maximum sum path
int MaximumPath(int Mat[][N]) {
   int result = 0 ;
   int dp[N][N+2];
   memset(dp, 0, sizeof(dp));
   for (int i = 0 ; i < N ; i++)
      dp[0][i+1] = Mat[0][i];
   for (int i = 1 ; i < N ; i++)
      for (int j = 1 ; j <= N ; j++)
         dp[i][j] = max(dp[i-1][j-1], max(dp[i-1][j], dp[i-1][j+1])) + Mat[i][j-1] ;
   for (int i=0; i<=N; i++)
      result = max(result, dp[N-1][i]);
   return result ;
}
int main() {
   int Mat[4][4] = {
      { 4, 2 , 3 , 4 },
      { 2 , 9 , 1 , 10},
      { 15, 1 , 3 , 0 },
      { 16 ,92, 41, 44 }
   };
   cout << MaximumPath ( Mat ) <<endl ;
   return 0;
}

Output

120
raja
Published on 09-Sep-2020 12:02:53

Was it helpful?
Not affiliated with Tutorialspoint
scroll top