# Maximum path sum in matrix in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a 2D matrix of size M*N. Our task is to create a program that will find the maximum path sum in the matrix.

Here, the maximum path sum in the matrix is defined as the sum of all elements for one row to the last row. The allowed moves for traversing the path are downward move and diagonal move. The start and endpoints can be any element of the first and last row of the matrix respectively.

Let's take an example to understand the problem

Input

matrix [][] =
3 5 9
1 7 2
4 8 6

Output − 24

Explanation − The maximum path will be 9 → 7 → 8.

To solve the problem, we will start from the top of the array and find the largest element of the first row, and store into maxSum. Then on traversing the matrix and find the max values that occur in the path. If the new values are greater update maxSum otherwise don't update. And once the whole matrix is traversed and the path is created return the maxSum.

## Example

Program to find the maximum path sum in matrix −

Live Demo

#include <iostream>
#define N 3
#define M 3
using namespace std;
int maxPathSum(int mat[][M]){
for (int i = 1; i < N; i++) {
for (int j = 0; j < M; j++) {
if (j > 0 && j < M - 1)
mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1],mat[i - 1][j + 1]));
else if (j > 0)
mat[i][j] += max(mat[i - 1][j],
mat[i - 1][j - 1]);
else if (j < M - 1)
mat[i][j] += max(mat[i - 1][j],
mat[i - 1][j + 1]);
}
}
int maxSum = mat[N-1][0];
for (int j = 1; j < M; j++)
maxSum = max(mat[N-1][j], maxSum);
return maxSum;
}
int main(){
int matrix[N][M] = {
{3, 5, 9 },
{1, 7, 2},
{4, 8, 6}};
cout<<"The maximum path sum of matrix is : "<<maxPathSum(matrix);
return 0;
}

## Output

The maximum path sum of matrix is : 24
Published on 21-Jan-2020 10:52:57