Maximum sum path in a Matrix - GeeksforGeeks

28 Feb, 2022
Given an n*m matrix, the task is to find the maximum sum of elements of cells starting from the cell (0, 0) to cell (n-1, m-1). However, the allowed moves are right, downwards or diagonally right, i.e, from location (i, j) next move can be (i+1, j), or, (i, j+1), or (i+1, j+1). Find the maximum sum of elements satisfying the allowed moves.Examples: 
Input:
mat[][] = {{100, -350, -200},
           {-100, -300, 700}}
Output: 500
Explanation: 
Path followed is 100 -> -300 -> 700

Input:
mat[][] = {{500, 100, 230},
           {1000, 300, 100},
           {200, 1000, 200}}
Explanation:
Path followed is 500 -> 1000 -> 300 -> 1000 -> 200
Naive Approach: Recursion
Going through the Naive approach by traversing every possible path. But, this is costly. So, use Dynamic Programming here in order to reduce the time complexity.
C++
Javascript
#include <bits/stdc++.h>using namespace std;#define N 100 // No of rows and columnsint n, m; // Declaring the matrix of maximum// 100 rows and 100 columnsint a[N][N]; // For storing current sumint current_sum = 0; // For continuous update of// maximum sum requiredint total_sum = 0; // Function to Input the matrix of size n*mvoid inputMatrix(){    n = 3;    m = 3;    a[0][0] = 500;    a[0][1] = 100;    a[0][2] = 230;    a[1][0] = 1000;    a[1][1] = 300;    a[1][2] = 100;    a[2][0] = 200;    a[2][1] = 1000;    a[2][2] = 200;} // Function to calculate maximum sum of pathint maximum_sum_path(int i, int j){    // Checking boundary condition    if (i == n - 1 && j == m - 1)        return a[i][j];       // Checking whether the position hasn't    // visited the last row or the last column.    // Making recursive call for all the possible    // moves from the current cell and then adding the    // maximum returned by the calls and updating it.    if (i < n - 1 & j < m - 1) {        int current_sum = max(maximum_sum_path(i, j + 1),                              max(                                  maximum_sum_path(i + 1, j + 1),                                  maximum_sum_path(i + 1, j)));        total_sum = a[i][j] + current_sum;    }     // Checking whether    // position has reached last row    else if (i == n - 1)        total_sum = a[i][j]                    + maximum_sum_path(i, j + 1);     // If the position is in the last column    else        total_sum = a[i][j]                    + maximum_sum_path(i + 1, j);     // Returning the updated maximum value    return total_sum;} // Driver Codeint main(){    inputMatrix();     // Calling the implemented function    int maximum_sum = maximum_sum_path(0, 0);     cout << maximum_sum;    return 0;}
<script> const N = 100 // No of rows and columnslet n, m; // Declaring the matrix of maximum// 100 rows and 100 columnslet a = new Array(N);for(let i=0;i<N;i++){    a[i] = new Array(N);} // For storing current sumlet current_sum = 0; // For continuous update of// maximum sum requiredlet total_sum = 0; // Function to Input the matrix of size n*mfunction inputMatrix(){    n = 3;    m = 3;    a[0][0] = 500;    a[0][1] = 100;    a[0][2] = 230;    a[1][0] = 1000;    a[1][1] = 300;    a[1][2] = 100;    a[2][0] = 200;    a[2][1] = 1000;    a[2][2] = 200;} // Function to calculate maximum sum of pathfunction maximum_sum_path(i, j){     // Checking boundary condition    if (i == n - 1 && j == m - 1)        return a[i][j];     // Checking whether the position hasn't    // visited the last row or the last column.    // Making recursive call for all the possible    // moves from the current cell and then adding the    // maximum returned by the calls and updating it.    if (i < n - 1 & j < m - 1) {        let current_sum = Math.max(maximum_sum_path(i, j + 1),                            Math.max(                                maximum_sum_path(i + 1, j + 1),                                maximum_sum_path(i + 1, j)));        total_sum = a[i][j] + current_sum;    }     // Checking whether    // position has reached last row    else if (i == n - 1)        total_sum = a[i][j]                    + maximum_sum_path(i, j + 1);     // If the position is in the last column    else        total_sum = a[i][j]                    + maximum_sum_path(i + 1, j);     // Returning the updated maximum value    return total_sum;} // Driver CodeinputMatrix(); // Calling the implemented functionlet maximum_sum = maximum_sum_path(0, 0); document.write(maximum_sum,"</br>"); // This code is contributed by shinjanpatra </script>
3000
Time Complexity: O(2N*M) 
Auxiliary Space: O(N*M)
Efficient Approach : Dynamic programming is used to solve the above problem in a recursive way.  
Allot a position at the beginning of the matrix at (0, 0).Check each next allowed position from the current position and select the path with maximum sum.Take care of the boundaries of the matrix, i.e, if the position reaches the last row or last column then the only possible choice will be right or downwards respectively.Use a map to store track of all the visiting positions and before visiting any (i, j), check whether or not the position is visited before.Update the maximum of all possible paths returned by each recursive calls made.Go till the position reaches the destination cell, i.e, (n-1.m-1).
Allot a position at the beginning of the matrix at (0, 0).
Check each next allowed position from the current position and select the path with maximum sum.
Take care of the boundaries of the matrix, i.e, if the position reaches the last row or last column then the only possible choice will be right or downwards respectively.
Use a map to store track of all the visiting positions and before visiting any (i, j), check whether or not the position is visited before.
Update the maximum of all possible paths returned by each recursive calls made.
Go till the position reaches the destination cell, i.e, (n-1.m-1).
Below is the implementation of the above approach: 
C++
Java
C#
Javascript
Python3
#include <bits/stdc++.h>using namespace std;#define N 100 // No of rows and columnsint n, m; // Declaring the matrix of maximum// 100 rows and 100 columnsint a[N][N]; // Variable visited is used to keep// track of all the visited positions// Variable dp is used to store// maximum sum till current positionvector<vector<int> > dp(N, vector<int>(N)),    visited(N, vector<int>(N)); // For storing current sumint current_sum = 0; // For continuous update of// maximum sum requiredint total_sum = 0; // Function to Input the matrix of size n*mvoid inputMatrix(){    n = 3;    m = 3;    a[0][0] = 500;    a[0][1] = 100;    a[0][2] = 230;    a[1][0] = 1000;    a[1][1] = 300;    a[1][2] = 100;    a[2][0] = 200;    a[2][1] = 1000;    a[2][2] = 200;} // Function to calculate maximum sum of pathint maximum_sum_path(int i, int j){    // Checking boundary condition    if (i == n - 1 && j == m - 1)        return a[i][j];     // Checking whether or not (i, j) is visited    if (visited[i][j])        return dp[i][j];     // Marking (i, j) is visited    visited[i][j] = 1;     // Updating the maximum sum till    // the current position in the dp    int& total_sum = dp[i][j];     // Checking whether the position hasn't    // visited the last row or the last column.    // Making recursive call for all the possible    // moves from the current cell and then adding the    // maximum returned by the calls and updating it.    if (i < n - 1 & j < m - 1) {        int current_sum = max(maximum_sum_path(i, j + 1),                              max(                                  maximum_sum_path(i + 1, j + 1),                                  maximum_sum_path(i + 1, j)));        total_sum = a[i][j] + current_sum;    }     // Checking whether    // position has reached last row    else if (i == n - 1)        total_sum = a[i][j]                    + maximum_sum_path(i, j + 1);     // If the position is in the last column    else        total_sum = a[i][j]                    + maximum_sum_path(i + 1, j);     // Returning the updated maximum value    return dp[i][j] = total_sum;} // Driver Codeint main(){    inputMatrix();     // Calling the implemented function    int maximum_sum = maximum_sum_path(0, 0);     cout << maximum_sum;    return 0;}
class GFG{     static final int N = 100; // No of rows and columnsstatic int n, m; // Declaring the matrix of maximum// 100 rows and 100 columnsstatic int a[][] = new int[N][N]; // Variable visited is used to keep// track of all the visited positions// Variable dp is used to store// maximum sum till current positionstatic int dp[][] = new int[N][N];static int visited[][] = new int[N][N]; // For storing current sumstatic int current_sum = 0; // For continuous update of// maximum sum requiredstatic int total_sum = 0; // Function to Input the matrix// of size n*mstatic void inputMatrix(){    n = 3;    m = 3;    a[0][0] = 500;    a[0][1] = 100;    a[0][2] = 230;    a[1][0] = 1000;    a[1][1] = 300;    a[1][2] = 100;    a[2][0] = 200;    a[2][1] = 1000;    a[2][2] = 200;} // Function to calculate maximum sum of pathstatic int maximum_sum_path(int i, int j){         // Checking boundary condition    if (i == n - 1 && j == m - 1)        return a[i][j];     // Checking whether or not    // (i, j) is visited    if (visited[i][j] != 0)        return dp[i][j];     // Marking (i, j) is visited    visited[i][j] = 1;     int total_sum = 0;     // Checking whether the position hasn't    // visited the last row or the last column.    // Making recursive call for all the possible    // moves from the current cell and then adding the    // maximum returned by the calls and updating it.    if (i < n - 1 & j < m - 1)    {        int current_sum = Math.max(                          maximum_sum_path(i, j + 1),                          Math.max(                          maximum_sum_path(i + 1, j + 1),                          maximum_sum_path(i + 1, j)));        total_sum = a[i][j] + current_sum;    }     // Checking whether position    // has reached last row    else if (i == n - 1)        total_sum = a[i][j] +                    maximum_sum_path(i, j + 1);     // If the position is in the last column    else        total_sum = a[i][j] +                    maximum_sum_path(i + 1, j);     // Updating the maximum sum till    // the current position in the dp    dp[i][j] = total_sum;     // Returning the updated maximum value    return total_sum;} // Driver Codepublic static void main(String[] args){    inputMatrix();     // Calling the implemented function    int maximum_sum = maximum_sum_path(0, 0);     System.out.println(maximum_sum);}} // This code is contributed by jrishabh99
// C# program to implement// the above approachusing System;class GFG{ static readonly int N = 100; // No of rows and columnsstatic int n, m; // Declaring the matrix of maximum// 100 rows and 100 columnsstatic int[,]a = new int[N, N]; // Variable visited is used to keep// track of all the visited positions// Variable dp is used to store// maximum sum till current positionstatic int [,]dp = new int[N, N];static int [,]visited = new int[N, N]; // For storing current sumstatic int current_sum = 0; // For continuous update of// maximum sum requiredstatic int total_sum = 0; // Function to Input the matrix// of size n*mstatic void inputMatrix(){  n = 3;  m = 3;  a[0, 0] = 500;  a[0, 1] = 100;  a[0, 2] = 230;  a[1, 0] = 1000;  a[1, 1] = 300;  a[1, 2] = 100;  a[2, 0] = 200;  a[2, 1] = 1000;  a[2, 2] = 200;} // Function to calculate maximum// sum of pathstatic int maximum_sum_path(int i,                            int j){  // Checking boundary condition  if (i == n - 1 && j == m - 1)    return a[i, j];   // Checking whether or not  // (i, j) is visited  if (visited[i, j] != 0)    return dp[i, j];   // Marking (i, j) is visited  visited[i, j] = 1;   int total_sum = 0;   // Checking whether the position  // hasn't visited the last row  // or the last column.  // Making recursive call for all  // the possible moves from the  // current cell and then adding the  // maximum returned by the calls  // and updating it.  if (i < n - 1 & j < m - 1)  {    int current_sum = Math.Max(maximum_sum_path(i, j + 1),                      Math.Max(maximum_sum_path(i + 1,                                                j + 1),                               maximum_sum_path(i + 1, j)));    total_sum = a[i, j] + current_sum;  }   // Checking whether position  // has reached last row  else if (i == n - 1)    total_sum = a[i, j] +                maximum_sum_path(i, j + 1);   // If the position is  // in the last column  else    total_sum = a[i, j] +                maximum_sum_path(i + 1, j);   // Updating the maximum  // sum till the current  // position in the dp  dp[i, j] = total_sum;   // Returning the updated  // maximum value  return total_sum;} // Driver Codepublic static void Main(String[] args){  inputMatrix();   // Calling the implemented function  int maximum_sum = maximum_sum_path(0, 0);   Console.WriteLine(maximum_sum);}} // This code is contributed by shikhasingrajput
<script>    // Javascript program to implement the above approach         let N = 100;      // No of rows and columns    let n, m;     // Declaring the matrix of maximum    // 100 rows and 100 columns    let a = new Array(N);     // Variable visited is used to keep    // track of all the visited positions    // Variable dp is used to store    // maximum sum till current position    let dp = new Array(N);    let visited = new Array(N);    for(let i = 0; i < N; i++)    {        a[i] = new Array(N);        dp[i] = new Array(N);        visited[i] = new Array(N);        for(let j = 0; j < N; j++)        {            a[i][j] = 0;            dp[i][j] = 0;            visited[i][j] = 0;        }    }     // For storing current sum    let current_sum = 0;     // For continuous update of    // maximum sum required    let total_sum = 0;     // Function to Input the matrix    // of size n*m    function inputMatrix()    {        n = 3;        m = 3;        a[0][0] = 500;        a[0][1] = 100;        a[0][2] = 230;        a[1][0] = 1000;        a[1][1] = 300;        a[1][2] = 100;        a[2][0] = 200;        a[2][1] = 1000;        a[2][2] = 200;    }     // Function to calculate maximum sum of path    function maximum_sum_path(i, j)    {         // Checking boundary condition        if (i == n - 1 && j == m - 1)            return a[i][j];         // Checking whether or not        // (i, j) is visited        if (visited[i][j] != 0)            return dp[i][j];         // Marking (i, j) is visited        visited[i][j] = 1;         let total_sum = 0;         // Checking whether the position hasn't        // visited the last row or the last column.        // Making recursive call for all the possible        // moves from the current cell and then adding the        // maximum returned by the calls and updating it.        if (i < n - 1 & j < m - 1)        {            let current_sum = Math.max(                              maximum_sum_path(i, j + 1),                              Math.max(                              maximum_sum_path(i + 1, j + 1),                              maximum_sum_path(i + 1, j)));            total_sum = a[i][j] + current_sum;        }         // Checking whether position        // has reached last row        else if (i == n - 1)            total_sum = a[i][j] + maximum_sum_path(i, j + 1);         // If the position is in the last column        else            total_sum = a[i][j] + maximum_sum_path(i + 1, j);         // Updating the maximum sum till        // the current position in the dp        dp[i][j] = total_sum;         // Returning the updated maximum value        return total_sum;    }         inputMatrix();      // Calling the implemented function    let maximum_sum = maximum_sum_path(0, 0);      document.write(maximum_sum); // This code is contributed by suresh07.</script>
N=100 # No of rows and columnsn, m=-1,-1 # Declaring the matrix of maximum# 100 rows and 100 columnsa=[[-1]*N for _ in range(N)] # Variable visited is used to keep# track of all the visited positions# Variable dp is used to store# maximum sum till current positiondp,visited=[[-1]*N for _ in range(N)],[[False]*N for _ in range(N)] # For storing current sumcurrent_sum = 0 # For continuous update of# maximum sum requiredtotal_sum = 0 # Function to Input the matrix of size n*mdef inputMatrix():    global n, m    n = 3    m = 3    a[0][0] = 500    a[0][1] = 100    a[0][2] = 230    a[1][0] = 1000    a[1][1] = 300    a[1][2] = 100    a[2][0] = 200    a[2][1] = 1000    a[2][2] = 200  # Function to calculate maximum sum of pathdef maximum_sum_path(i, j):    global total_sum    # Checking boundary condition    if (i == n - 1 and j == m - 1):        return a[i][j]     # Checking whether or not (i, j) is visited    if (visited[i][j]):        return dp[i][j]     # Marking (i, j) is visited    visited[i][j] = True     # Updating the maximum sum till    # the current position in the dp    total_sum = dp[i][j]     # Checking whether the position hasn't    # visited the last row or the last column.    # Making recursive call for all the possible    # moves from the current cell and then adding the    # maximum returned by the calls and updating it.    if (i < n - 1 and j < m - 1) :        current_sum = max(maximum_sum_path(i, j + 1),                              max(                                  maximum_sum_path(i + 1, j + 1),                                  maximum_sum_path(i + 1, j)))        total_sum = a[i][j] + current_sum          # Checking whether    # position has reached last row    elif (i == n - 1):        total_sum = a[i][j] + maximum_sum_path(i, j + 1)     # If the position is in the last column    else:        total_sum = a[i][j] + maximum_sum_path(i + 1, j)     # Returning the updated maximum value    dp[i][j] = total_sum    return total_sum  # Driver Codeif __name__ == '__main__':    inputMatrix()     # Calling the implemented function    maximum_sum = maximum_sum_path(0, 0)     print(maximum_sum)
3000
Time Complexity: O(N*M)Auxiliary Space: O(N*M)
jrishabh99
silentRanger
shikhasingrajput
pikachuthedecipher
suresh07
amartyaghoshgfg
prasanna1995
shinjanpatra
Algorithms
Data Structures
Dynamic Programming
Matrix
Recursion
Data Structures
Dynamic Programming
Recursion
Matrix
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
Introduction to Algorithms
How to Start Learning DSA?