Maximum path sum in matrix (original) (raw)

Given a matrix of size n * m. Find the maximum path sum in the matrix. The maximum path is the sum of all elements from the first row to the last row where you are allowed to move only down or diagonally to left or right. You can start from any element in the first row.

**Examples:

**Input: mat[][] = 10 10 2 0 20 4
1 0 0 30 2 5
0 10 4 0 2 0
1 0 2 20 0 4
**Output: 74
**Explanation: The maximum sum path is 20-30-4-20.

**Input: mat[][] = 1 2 3
9 8 7
4 5 6
**Output: 17
**Explanation: The maximum sum path is 3-8-6.

**Approach:

The idea is to use dynamic programming to calculate the maximum path sum in a matrix. Starting from the first row, for each cell in the matrix, we update its value by adding the maximum of the possible moves from the previous row (up, left, right). This way, we propagate the maximum possible sum at each step. Finally, we find the maximum value in the last row and return it as the result.

Below is the implementation of the above approach:

C++ `

// Approach: Dynamic Programming // Language: C++

#include <bits/stdc++.h> using namespace std;

// Function to find the maximum path sum int maximumPath(vector<vector>& mat) { int n = mat.size(), m = mat[0].size();

// Initialize result with the maximum value in the first row
int res = *max_element(mat[0].begin(), mat[0].end());

// Traverse the matrix row by row
for (int i = 1; i < n; i++) {
    for (int j = 0; j < m; j++) {
        // Get max value from possible previous row positions
        int up = mat[i - 1][j];
        int left = (j > 0) ? mat[i - 1][j - 1] : 0;
        int right = (j < m - 1) ? mat[i - 1][j + 1] : 0;
        
        // Update current cell with max path sum
        mat[i][j] += max({up, left, right});
        
        // Update result if current cell has a greater value
        res = max(res, mat[i][j]);
    }
}
return res;

}

int main() {

// Input matrix
vector<vector<int>> mat = {{10, 10,  2,  0, 20,  4},
                            { 1,  0,  0, 30,  2,  5},
                            { 0, 10,  4,  0,  2,  0},
                            { 1,  0,  2, 20,  0,  4}};

// Output the maximum path sum
cout << maximumPath(mat) << endl;
return 0;

}

Java

// Approach: Dynamic Programming // Language: Java import java.util.*;

class GfG { // Function to find the maximum path sum public static int maximumPath(int[][] mat) { int n = mat.length, m = mat[0].length;

    // Initialize result with the maximum value in the first row
    int res = Arrays.stream(mat[0]).max().getAsInt();
    
    // Traverse the matrix row by row
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < m; j++) {
            // Get max value from possible previous row positions
            int up = mat[i - 1][j];
            int left = (j > 0) ? mat[i - 1][j - 1] : 0;
            int right = (j < m - 1) ? mat[i - 1][j + 1] : 0;
            
            // Update current cell with max path sum
            mat[i][j] += Math.max(up, Math.max(left, right));
            
            // Update result if current cell has a greater value
            res = Math.max(res, mat[i][j]);
        }
    }
    return res;
}

public static void main(String[] args) {
  
    // Input matrix
    int[][] mat = {
        {10, 10,  2,  0, 20,  4},
        { 1,  0,  0, 30,  2,  5},
        { 0, 10,  4,  0,  2,  0},
        { 1,  0,  2, 20,  0,  4}
    };
    
    // Output the maximum path sum
    System.out.println(maximumPath(mat));
}

}

Python

Approach: Dynamic Programming

Language: Python

def maximum_path(mat): n = len(mat) m = len(mat[0])

# Initialize result with the maximum value in the first row
res = max(mat[0])

# Traverse the matrix row by row
for i in range(1, n):
    for j in range(m):
        # Get max value from possible previous row positions
        up = mat[i - 1][j]
        left = mat[i - 1][j - 1] if j > 0 else 0
        right = mat[i - 1][j + 1] if j < m - 1 else 0
        
        # Update current cell with max path sum
        mat[i][j] += max(up, left, right)
        
        # Update result if current cell has a greater value
        res = max(res, mat[i][j])

return res

Input matrix

mat = [ [10, 10, 2, 0, 20, 4], [1, 0, 0, 30, 2, 5], [0, 10, 4, 0, 2, 0], [1, 0, 2, 20, 0, 4] ]

Output the maximum path sum

print(maximum_path(mat))

C#

// Approach: Dynamic Programming // Language: C# using System; using System.Linq;

class GfG {

// Function to find the maximum path sum
static int MaximumPath(int[,] mat) {
    int n = mat.GetLength(0), m = mat.GetLength(1);
    
    // Initialize result with the maximum value in the first row
    int res = mat.Cast<int>().Take(m).Max();
    
    // Traverse the matrix row by row
    for (int i = 1; i < n; i++) {
        for (int j = 0; j < m; j++) {
            // Get max value from possible previous row positions
            int up = mat[i - 1, j];
            int left = (j > 0) ? mat[i - 1, j - 1] : 0;
            int right = (j < m - 1) ? mat[i - 1, j + 1] : 0;
            
            // Update current cell with max path sum
            mat[i, j] += Math.Max(Math.Max(up, left), right);
            
            // Update result if current cell has a greater value
            res = Math.Max(res, mat[i, j]);
        }
    }
    return res;
}

static void Main() {
  
    // Input matrix
    int[,] mat = {
        {10, 10, 2, 0, 20, 4},
        {1, 0, 0, 30, 2, 5},
        {0, 10, 4, 0, 2, 0},
        {1, 0, 2, 20, 0, 4}
    };
    
    // Output the maximum path sum
    Console.WriteLine(MaximumPath(mat));
}

}

JavaScript

// Approach: Dynamic Programming // Language: JavaScript

function maximumPath(mat) { let n = mat.length, m = mat[0].length;

// Initialize result with the maximum value in the first row
let res = Math.max(...mat[0]);

// Traverse the matrix row by row
for (let i = 1; i < n; i++) {
    for (let j = 0; j < m; j++) {
        // Get max value from possible previous row positions
        let up = mat[i - 1][j];
        let left = (j > 0) ? mat[i - 1][j - 1] : 0;
        let right = (j < m - 1) ? mat[i - 1][j + 1] : 0;
        
        // Update current cell with max path sum
        mat[i][j] += Math.max(up, left, right);
        
        // Update result if current cell has a greater value
        res = Math.max(res, mat[i][j]);
    }
}
return res;

}

// Input matrix let mat = [ [10, 10, 2, 0, 20, 4], [1, 0, 0, 30, 2, 5], [0, 10, 4, 0, 2, 0], [1, 0, 2, 20, 0, 4] ];

// Output the maximum path sum console.log(maximumPath(mat));

`

**Time Complexity: O(n * m), where n is the number of rows and m is the number of columns, as we traverse the matrix once.
**Auxiliary Space: O(1), since the matrix is updated in-place without using extra space.