Maximum weight path ending at any element of last row in a matrix in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an integer n and a matrix of size n X n which contains the weight of the cell. Our task is to create a program that will find the maximum weight path ending at any element of the last row in a matrix. While finding the path the traversal will start from top-left (0,0) and the valid moves will be down and diagonal, no left move is allowed.

Let’s take an example to understand the problem,

Input

n = 3
Mat[3][3] ={
   {4, 3, 1}
   {5, 8, 9}
   {6, 7, 2}}

Output 

19

Explanation

All paths that can be used will be
Path1: 4+5+6 = 15
Path2: 4+8+7 = 19
Path3: 4+8+2 = 12
Path4: 4+5+7 = 16

As out of these the best possible path is path2 with weight 19

So, one possible solution can be calculating all paths and then compare them, but this will be an inefficient approach when n large number.

An effective solution will be using dynamic programming as this is a type of overlapping problem. Starting from the root their are n branches that can provide the desired result.

We will create a matrix that will store the maximum weight of the given paths that are traversed to reach that cell in the matrix.

This we will which is the maximum sum in the last row of the matrix and print it.

Example

Program to solve the problem,

 Live Demo

#include<bits/stdc++.h>
using namespace std;
const int MAX = 1000;
int maxCost(int matrix[][MAX], int N) {
   int sumMat[N][N];
   memset(sumMat, 0, sizeof(sumMat));
   int maxSum = 0;
   sumMat[0][0] = matrix[0][0];
   for (int i=1; i<N; i++)
      sumMat[i][0] = matrix[i][0] + sumMat[i-1][0];
   for (int i=1; i<N; i++)
   for (int j=1; j<i+1&&j<N; j++)
      sumMat[i][j] = matrix[i][j] + max(sumMat[i-1][j-1], sumMat[i-1][j]);
   for (int i=0; i<N; i++)
      if (maxSum < sumMat[N-1][i]) maxSum = sumMat[N-1][i];
      return maxSum;
}
int main(){
   int mat[MAX][MAX] ={
      {5 , 6 , 1 },
      {2 , 11 , 10 },
      {15, 3 , 2 }};
   int N = 3;
   cout<<"Maximum Path Sum for top-left cell to last row is : "<<maxCost(mat, N)<<endl;
   return 0;
}

Output

Maximum Path Sum for top-left cell to last row is : 22
raja
Published on 10-Feb-2020 14:14:36
Advertisements