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

C++Server Side ProgrammingProgramming

Problem statement

Given a matrix of integers where every element represents the weight of the cell. Find the path having the maximum weight in the matrix [N X N]. Path Traversal Rules are −

  • It should begin from the top left element.

  • The path can end at any element of the last row.

  • We can move to follow two cells from a cell (i, j).

    • Down Move: (i+1, j)

    • Diagonal Move: (i+1, j+1)

Consider below matrix −

matrix[5][5] = {
   {14, 12 ,3 ,14, 10},
   {20, 19 ,11 ,10 ,51},
   {15, 11, 31, 90 ,20},
   {16 ,12, 31, 41 ,12},
   {18, 24, 16, 40, 80}
};
Then Output is 185

Algorithms

We can solve this problem using recursion −

1. Let maxCost(i, j) be the cost maximum cost to reach mat[i][j]. Since end point can
   be any point in last row, we finally return maximum of all values maxCost(N-1, j) where
   j varies from 0 to N-1
2. If i == 0 and j == 0 then maxCost(0, 0) = mat[0][0]
3. Else if j = 0 maxCost(i, 0) = maxCost(i-1, 0) + mat[i][0]
4. Else maxCost(i, j) = mat[i][j] + max(maxCost(i-1, j), maxCost(i-1, j-1))

Example

#include<bits/stdc++.h>
using namespace std;
const int MAX = 1000;
int maxCost(int matrix[][MAX], int n){
   int dp[n][n];
   memset(dp, 0, sizeof(dp));
   dp[0][0] = matrix[0][0];
   for (int i = 1; i < n; ++i) {
      dp[i][0] = matrix[i][0] + dp[i-1][0];
   }
   for (int i = 1; i < n; ++i) {
      for (int j = 1; j < i + 1 && j < n; ++j){
         dp[i][j] = matrix[i][j] +
         max(dp[i-1][j-1], dp[i-1][j]);
      }
   }
   int result = 0;
   for (int i = 0; i < n; ++i) {
      if (result < dp[n-1][i]){
         result = dp[n-1][i];
      }
   }
   return result;
}
int main(){
   int matrix[MAX][MAX] = {
      {14, 12, 3, 14, 10 },
      {20, 19, 11, 10, 51 },
      {15, 11, 31, 90, 20 },
      {16, 12, 31, 41, 12},
      {18, 24, 16, 40, 80}
   };
   int n = 5;
   cout << "Maximum path sum = " << maxCost(matrix, n) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

Maximum path sum = 185
raja
Published on 10-Feb-2020 09:44:36
Advertisements