The Wayback Machine - https://web.archive.org/web/20240927175947/https://www.geeksforgeeks.org/maximum-sum-path-in-a-matrix/
Open In App

Maximum sum path in a Matrix

Last Updated : 02 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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++




#include <bits/stdc++.h>
using namespace std;
#define N 100
 
// No of rows and columns
int n, m;
 
// Declaring the matrix of maximum
// 100 rows and 100 columns
int a[N][N];
 
// For storing current sum
int current_sum = 0;
 
// For continuous update of
// maximum sum required
int total_sum = 0;
 
// Function to Input the matrix of size n*m
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 path
int 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 Code
int main()
{
    inputMatrix();
 
    // Calling the implemented function
    int maximum_sum = maximum_sum_path(0, 0);
 
    cout << maximum_sum;
    return 0;
}


Java




// Java program for
// Recursive implementation of
// Max sum path
import java.io.*;
 
class GFG {
 
    // Function for finding maximum sum
    public static int maxPathSum(int matrix[][], int i, int j)
    {
         
        if (i<0 || j<0) {
          return -100_000_000;
        }
        if (i==0 && j==0) {
            return matrix[i][j];
        }
         
          int up = matrix[i][j] + maxPathSum(matrix, i - 1, j);
        int right = matrix[i][j] + maxPathSum(matrix, i, j - 1);
        int up_left_diagonal = matrix[i][j] + maxPathSum(matrix, i - 1, j - 1);
        return  Math.max(up , Math.max( right, up_left_diagonal));
    }
 
    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        int matrix [][] ={{100, -350, -200}, {-100, -300, 700}};
        System.out.print(maxPathSum(matrix, 1, 2));
    }
}
 
// This code is contributed by Rohini Chandra


Python3




# No of rows and columns
n = 0
m = 0
# Declaring the matrix of maximum
# 100 rows and 100 columns
rows, cols = (100, 100)
a = [[0 for i in range(cols)] for j in range(rows)]
 
# For storing current sum
current_sum = 0
 
# For continuous update of
# maximum sum required
total_sum = 0
 
# Function to Input the matrix of size n*m
 
 
def inputMatrix():
  global n, m, a
  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
def maximum_sum_path(i, j):
  global n, m, a, total_sum, current_sum
 
  # Checking boundary condition
  if i == n - 1 and 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)):
      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
  return total_sum
 
 
# Driver program
if __name__ == "__main__":
  inputMatrix()
 
  # Calling the implemented function
  maximum_sum = maximum_sum_path(0, 0)
 
  print(maximum_sum)


C#




using System;
using System.Collections.Generic;
 
class GFG
{
 
  static readonly int N= 100;
 
  // No of rows and columns
  static int n, m;
 
  // Declaring the matrix of maximum
  // 100 rows and 100 columns
  static int[,]a = new int[N, N];
 
  // For storing current sum
  static int current_sum = 0;
 
  // For continuous update of
  // maximum sum required
  static int total_sum = 0;
 
  // Function to Input the matrix of size n*m
  static 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 path
  static int 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 = 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 Code
  static void Main(string[] args)
  {
    inputMatrix();
 
    // Calling the implemented function
    int maximum_sum = maximum_sum_path(0, 0);
    Console.Write(maximum_sum);
  }
}


Javascript




<script>
 
const 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);
for(let i=0;i<N;i++){
    a[i] = new Array(N);
}
 
// 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 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 Code
inputMatrix();
 
// Calling the implemented function
let maximum_sum = maximum_sum_path(0, 0);
 
document.write(maximum_sum,"</br>");
 
// This code is contributed by shinjanpatra
 
</script>


Output

3000

Time Complexity: O(2N*M) 

Auxiliary Space: O(N*M)

2. Efficient Approach(Memoization) : Dynamic programming is used to solve the above problem in a recursive way.  

  1. Allot a position at the beginning of the matrix at (0, 0).
  2. Check each next allowed position from the current position and select the path with maximum sum.
  3. 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.
  4. 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.
  5. Update the maximum of all possible paths returned by each recursive calls made.
  6. Go till the position reaches the destination cell, i.e, (n-1.m-1).

Below is the implementation of the above approach: 

C++




#include <bits/stdc++.h>
using namespace std;
#define N 100
 
// No of rows and columns
int n, m;
 
// Declaring the matrix of maximum
// 100 rows and 100 columns
int 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 position
vector<vector<int> > dp(N, vector<int>(N)),
    visited(N, vector<int>(N));
 
// For storing current sum
int current_sum = 0;
 
// For continuous update of
// maximum sum required
int total_sum = 0;
 
// Function to Input the matrix of size n*m
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 path
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])
        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 Code
int main()
{
    inputMatrix();
 
    // Calling the implemented function
    int maximum_sum = maximum_sum_path(0, 0);
 
    cout << maximum_sum;
    return 0;
}


Java




class GFG{
     
static final int N = 100;
 
// No of rows and columns
static int n, m;
 
// Declaring the matrix of maximum
// 100 rows and 100 columns
static 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 position
static int dp[][] = new int[N][N];
static int visited[][] = new int[N][N];
 
// For storing current sum
static int current_sum = 0;
 
// For continuous update of
// maximum sum required
static int total_sum = 0;
 
// Function to Input the matrix
// of size n*m
static 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 path
static 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 Code
public 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


Python3




N=100
 
# No of rows and columns
n, m=-1,-1
 
# Declaring the matrix of maximum
# 100 rows and 100 columns
a=[[-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 position
dp,visited=[[-1]*N for _ in range(N)],[[False]*N for _ in range(N)]
 
# For storing current sum
current_sum = 0
 
# For continuous update of
# maximum sum required
total_sum = 0
 
# Function to Input the matrix of size n*m
def 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 path
def 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 Code
if __name__ == '__main__':
    inputMatrix()
 
    # Calling the implemented function
    maximum_sum = maximum_sum_path(0, 0)
 
    print(maximum_sum)


C#




// C# program to implement
// the above approach
using System;
class GFG{
 
static readonly int N = 100;
 
// No of rows and columns
static int n, m;
 
// Declaring the matrix of maximum
// 100 rows and 100 columns
static 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 position
static int [,]dp = new int[N, N];
static int [,]visited = new int[N, N];
 
// For storing current sum
static int current_sum = 0;
 
// For continuous update of
// maximum sum required
static int total_sum = 0;
 
// Function to Input the matrix
// of size n*m
static 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 path
static 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 Code
public 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


Javascript




<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>


Output

3000

Time Complexity: O(N*M)
Auxiliary Space: O(N*M) + O(N+M) -> O(NxM) is for the declared matrix of size nxm and O(N+M) is for the stack space (maximum recursive recursion calls).

3. Tabulation approach: This approach will remove the extra space complexity i.e O(N+M) caused by recursion in the above approach. 

  1. Declare an array of size NxM – dp[N][M].
  2. Traverse through the created array row-wise and start filling the values in it.
  3. First row of the `dp` array i.e. index (0,j) ,where j represents column, will contain the values same as the first row of the given `matrix` array.
  4. Otherwise, we will calculate the values for up (i-1,j), right (i,j-1) and up_left_diagonal (i-1,j-1) for the current cell and the maximum value of them will be the value for the current cell ie dp[i][j].
  5. Finally, the maximum path sum of the matrix will be at dp[n-1][m-1] where n=no. of rows and m=no. of columns.

C++




// C++ program for
// Recursive implementation of
// Max sum path
#include <bits/stdc++.h>
using namespace std;
 
int maxPathSum(int matrix[2][3], int i, int j)
{
  if (i < 0 || j < 0) {
    return -1000000000;
  }
  if (i == 0 && j == 0) {
    return matrix[i][j];
  }
 
  int up = matrix[i][j] + maxPathSum(matrix, i - 1, j);
  int right = matrix[i][j] + maxPathSum(matrix, i, j - 1);
  int up_left_diagonal
    = matrix[i][j] + maxPathSum(matrix, i - 1, j - 1);
  return max(up, max(right, up_left_diagonal));
}
 
int main()
{
  int matrix[2][3]
    = { { 100, -350, -200 }, { -100, -300, 700 } };
  cout << maxPathSum(matrix, 1, 2) << endl;
  return 0;
}
 
//  // This code is contributed by lokeshpotta20.


Java




// Java program for
// Recursive implementation of
// Max sum path
import java.io.*;
 
class GFG {
 
    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        int matrix [][] = {{100, -350, -200}, {-100, -300, 700}};
        int n = matrix.length;
        int m = matrix[0].length;
        int dp[][] = new int [n][m], up, right, up_left_diagonal;
        for (int i=0; i<n; i++){
            for (int j=0; j<m; j++){
                 if (i==0) {
                    dp[i][j] = matrix[i][j];
                 }
                 else {
                    
                    up = matrix[i][j];
                    if(i>0) up += dp[i-1][j];
                    else up -= (int)Math.pow(10,9);
                    
                    right = matrix[i][j];
                    if(j>0) right += dp[i][j-1];
                    else right -= (int)Math.pow(10,9);
                     
                    up_left_diagonal = matrix[i][j];
                    if(i>0 && j>0) up_left_diagonal += dp[i-1][j-1];
                    else up_left_diagonal -= (int)Math.pow(10,9);
                    
                    dp[i][j] = Math.max(up , Math.max( right, up_left_diagonal));
                 }
            }
        }
        System.out.println(dp[n-1][m-1]);
    }
}
 
// This code is contributed by Rohini Chandra


Python3




# Python program for Recursive implementation of Max sum path
 
# Function for finding maximum sum
def maxPathSum(matrix, i, j):
    if i < 0 or j < 0:
        return -1000000000
    if i == 0 and j == 0:
        return matrix[i][j]
 
    up = matrix[i][j] + maxPathSum(matrix, i - 1, j)
    right = matrix[i][j] + maxPathSum(matrix, i, j - 1)
    up_left_diagonal = matrix[i][j] + maxPathSum(matrix, i - 1, j - 1)
    return max(up, max(right, up_left_diagonal))
 
 
matrix = [[100, -350, -200], [-100, -300, 700]]
print(maxPathSum(matrix, 1, 2))
 
# This code is contributed by sankar


C#




// C# program for
// Recursive implementation of
// Max sum path
using System;
 
class GFG
{
    // Function for finding maximum sum
    public static int maxPathSum(int[,] matrix, int i, int j)
    {
         
        if (i<0 || j<0) {
          return -1000000000;
        }
        if (i==0 && j==0) {
            return matrix[i,j];
        }
         
          int up = matrix[i,j] + maxPathSum(matrix, i - 1, j);
        int right = matrix[i,j] + maxPathSum(matrix, i, j - 1);
        int up_left_diagonal = matrix[i,j] + maxPathSum(matrix, i - 1, j - 1);
        return  Math.Max(up , Math.Max( right, up_left_diagonal));
    }
 
    /* Driver program to test above functions */
    public static void Main(string[] args)
    {
        int[,] matrix = {{100, -350, -200}, {-100, -300, 700}};
        Console.Write(maxPathSum(matrix, 1, 2));
    }
}


Javascript




// JavaScript program for
// Recursive implementation of
// Max sum path
function maxPathSum(matrix, i, j) {
if (i < 0 || j < 0) {
return -1000000000;
}
if (i === 0 && j === 0) {
return matrix[i][j];
}
 
const up = matrix[i][j] + maxPathSum(matrix, i - 1, j);
const right = matrix[i][j] + maxPathSum(matrix, i, j - 1);
const up_left_diagonal = matrix[i][j] + maxPathSum(matrix, i - 1, j - 1);
 
return Math.max(up, Math.max(right, up_left_diagonal));
}
 
// Driver code
const matrix = [[100, -350, -200], [-100, -300, 700]];
console.log(maxPathSum(matrix, 1, 2));


Output

500

Time complexity: O(NxM)

Auxiliary Space: O(NxM)



Similar Reads

Minimum cost such that path sum is at max K (Target Path Sum)
Given a rooted tree consisting of N vertices. The vertices are numbered from 0 to N-1, and the root is the vertex 0. You are also given a value array Arr: Arr0, Arr1,....., Arrn-1. You can do any of these moves any number of times: Pick any node that is not root cut the edge between it and its parent and connect an edge between this node to the roo
11 min read
Maximum sum path in a matrix from top to bottom and back
Given a matrix of dimension N * M. The task is find the maximum sum of path from arr[0][0] to arr[N - 1][M - 1] and back from arr[N - 1][M - 1] to arr[0][0]. On the path from arr[0][0] to arr[N - 1][M - 1], you can traverse in down and right directions and on the path from arr[N - 1][M - 1] to arr[0][0], you can traverse in up and left directions.
9 min read
Paths from entry to exit in matrix and maximum path sum
Given a maze which is a N * N grid grid[][]. Every cell of the maze contains either the number 1, 2 or 3 which defines the moves as: If grid[i][j] = 1 then the only valid move is grid[i][j + 1].If grid[i][j] = 2 then the only valid move is grid[i + 1][j].If grid[i][j] = 3 then the valid moves are grid[i][j + 1] and grid[i + 1][j]. Now, the task is
15 min read
Find maximum path sum in a 2D matrix when exactly two left moves are allowed
Given a 2D matrix arr[][] of dimensions N * M where N is number of rows and M is number of columns.The task is to find maximum path sum in this matrix satisfying some condition which are as follows : We can only start with arr[i][M] where 0 <= i <= N.We end the path on the same side, such that we can take exactly 2 left turns.First we calcula
2 min read
Maximum sum path in a matrix from top-left to bottom-right
Given a matrix mat[][] of dimensions N * M, the task is to find the path from the top-left cell (0, 0) to the bottom-right cell (N - 1, M - 1) of the given matrix such that sum of the elements in the path is maximum. The only moves allowed from any cell (i, j) of the matrix are (i + 1, j) or (i, j + 1). Examples: Input: mat[][] = {{3, 7}, {9, 8}}Ou
12 min read
Maximum path sum from top left to bottom right of a matrix passing through one of the given cells
Given a matrix mat[][] of dimensions N * M and a set of coordinates of cell coordinates[][] of size Q, the task is to find the maximum sum of a path from the top-left cell (1, 1) to the bottom-right cell (N, M), such that the path should contain at least one of the coordinates from the array coordinates[][2]. The only moves allowed from any cell (i
15 min read
Find the maximum sum path in the given Matrix
Consider an infinite matrix. The cells of the matrix are filled with natural numbers from the cell (1, 1) in the direction of top right to bottom left diagonally. Then the task is to output the Maximum path sum between two points (X1, Y1) and (X2, Y2). Matrix filling process is as follows: Examples: Input: X1 = 1, Y1 = 1, X2 = 3, Y2 = 3 Output: 32E
7 min read
Maximum sum path in a matrix from top to bottom
Consider a n*n matrix. Suppose each cell in the matrix has a value assigned. We can go from each cell in row i to a diagonally higher cell in row i+1 only [i.e from cell(i, j) to cell(i+1, j-1) and cell(i+1, j+1) only]. Find the path from the top row to the bottom row following the aforementioned condition such that the maximum sum is obtained. Exa
15 min read
Maximum path sum in matrix
Given a matrix of 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 4Outp
8 min read
Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path
Given an N-ary tree consisting of N nodes numbered from 1 to N rooted at node 1, the task is to assign values to each node of the tree such that the sum of values from any root to the leaf path which contains at least two nodes is not divisible by the number of nodes along that path. Examples: Input: N = 11, edges[][] = {{1, 2}, {1, 3}, {1, 4}, {1,
11 min read
Find maximum path length in a binary matrix
Given a square matrix mat every element of which is either 0 or 1. A value 1 means connected and 0 means not connected. The task is to find the largest length of a path in the matrix after changing atmost one 0 to 1. A path is a 4-directionally connected group of 1s. Examples: Input: mat[][] = {{1, 1}, {1, 0}} Output: 4 Change the only 0 to 1 and t
9 min read
Find the length of maximum path in given matrix for each index
Given a binary square matrix of characters having size N x N such that 1 represents land and 0 represents water, the task is to find the longest straight-line path a person can travel on land without falling into water or outside for each cell (i, j). The straight line can be either horizontal, vertical, or diagonal. Examples: Input: N = 4, matrix[
15+ min read
Maximum non-negative product of a path from top left to bottom right of given Matrix
Given an integer matrix mat[][] of dimensions N * M, the task is to print the maximum product of matrix elements in the path from the top-left cell (0, 0) to the bottom-right cell (N – 1, M – 1) of the given matrix. Only possible moves from any cell (i, j) is (i + 1, j) or (i, j + 1). If the maximum product is negative, then print "-1". Examples: I
10 min read
Maximum coin in minimum time by skipping K obstacles along path in Matrix
Given a 2D matrix, where '*' represents an obstacle and the rest all represent coins in the grid. It is also given that you are currently on grid[i1][ j1] and want to reach grid[i2][j2] by skipping at most K obstacles in the path, the task is to collect the maximum coin while reaching grid[i2][j2] in a minimum amount of time. Note: Only movements i
14 min read
Maximum XOR of a path from top-left to bottom-right cell of given Matrix
Given a matrix, mat[][] of dimensions N * M, the task is to print the maximum bitwise XOR value that can be obtained for a path from the top-left cell (0, 0) to the bottom-right cell (N - 1, M - 1) of the given matrix. Only possible moves from any cell (i, j) are (i + 1, j) and (i, j + 1). Note: Bitwise XOR value of a path is defined as the bitwise
9 min read
Maximum weight path ending at any element of last row in a matrix
Given a matrix of integers where every element represents the weight of the cell. Find the path having the maximum weight in matrix [N X N]. Path Traversal Rules are: It should begin from top left element.The path can end at any element of 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) Ex
15 min read
Maximum decimal value path in a binary matrix
Given binary square matrix [n*n]. Find maximum integer value in a path from top left to bottom right. We compute integer value using bits of traversed path. We start at index [0,0] and end at index [n-1][n-1]. from index [i, j], we can move [i, j+1] or [i+1, j]. Examples: Input : mat[][] = {{1, 1, 0, 1}, {0, 1, 1, 0}, {1, 0, 0, 1}, {1, 0, 1, 1}} Ou
14 min read
Check if a path exists from a given cell to any boundary element of the Matrix with sum of elements not exceeding K
Given a matrix grid[][] of dimensions M * N, three integers X, Y, and K, the task is to check if there exists any path from the cell (X, Y) to any boundary cell of the matrix such that sum of the matrix elements present in the path is at most K. If no such path exists, print "No". Otherwise, print "Yes". Possible moves from any cell are up, down, l
11 min read
Maximise matrix sum by following the given Path
Given a 2d-matrix mat[][] consisting of positive integers, the task is to find the maximum score we can reach if we have to go to cell mat[0][N - 1] starting from mat[0][0]. We have to cover the matrix in two phases: Phase 1: If we are at cell mat[i][j] then we can only go to cells mat[i][j + 1] or mat[i + 1][j] without changing the phase else we c
9 min read
Maximize path sum from top-left cell to all other cells of a given Matrix
Given a matrix, mat[][] of dimensions N * M, the task is to find the maximum path sum from the top-left cell (0, 0) to all other cells of the given matrix. Only possible moves from any cell (i, j) is (i + 1, j) and (i, j + 1). Examples: Input: mat[][] = {{3, 2, 1}, {6, 5, 4}, {7, 8, 9}}Output:3 5 69 14 1816 24 33Explanation:Path from (0, 0) to (0,
8 min read
Find if path from top-left to bottom-right with sum X exists in given Matrix
Given a matrix A[][] of size N * N, where each matrix element is either -1 or 1. One can move from (X, Y) to either (X + 1, Y) or (X, Y + 1) but not out of the matrix. The task is to check whether a path exists from the top-left to the bottom-right corner such that the sum of all elements in the path is X. Examples: Input: arr[][] = {{1, 1, 1, 1},
13 min read
Find the path from root to a vertex such that all K vertices belongs to this path or 1 distance away
Given a tree consisting of N vertices numbered from 1 to N rooted at vertex 1. You are given Q queries. Each query consists of the set of K distinct vertices vi[1], vi[2],â€Ķ, vi[K]. The task is to determine if there is a path from the root to some vertex X such that each of the given K vertices either belongs to this path or has the distance 1 to so
10 min read
Shortest path from source to destination such that edge weights along path are alternatively increasing and decreasing
Given a connected graph with N vertices and M edges. The task is to find the shortest path from source to the destination vertex such that the difference between adjacent edge weights in the shortest path change from positive to negative and vice versa ( Weight(E1) > Weight(E2) < Weight(E3) .... ). If no such path exists then print -1. Exampl
13 min read
Difference Between Hamiltonian Path and Eulerian Path
The Hamiltonian and Eulerian paths are two significant concepts used to the solve various problems related to the traversal and connectivity of the graphs. Understanding the differences between these two types of the paths is crucial for the designing efficient algorithms and solving the complex graph problems. What is a Hamiltonian Path?Hamiltonia
2 min read
Path with smallest difference between consecutive cells (Path with minimum effort)
Given a 2D array arr[] of size N x M, where arr[i][j] represents the value of cell (i, j). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (n-1, m-1). You can move up, down, left, or right, and you wish to find a path such that the maximum absolute difference in values between two consecutive cells of
14 min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Maximum path sum in an Inverted triangle | SET 2
Given numbers in form of an Inverted triangle. By starting at the bottom of the triangle and moving to adjacent numbers on the row above, find the maximum total from bottom to top.Examples: Input : 1 5 3 4 8 1 Output : 14 Input : 8 5 9 3 2 4 6 7 4 3 Output : 23 Method 1: Recursion In the previous article we saw an approach of the problem where the
13 min read
Maximum path sum when at most K elements can be picked from a row
Given a matrix mat[][] of size N * M and an integer K, the task is to find a path from the top-left cell (0, 0) to the bottom-right cell (N–1, M–1) of the given matrix such that: One right and downward movement are allowed. i.e., from (i, j) to (i, j-1) and (i+1, j). Sum of the elements in the path is maximum and not more than K cells can be chosen
14 min read
Maximum Path sum in a N-ary Tree
Given an undirected tree with N nodes numbered from 1 to N and an array A[] where A[i] denotes the value assigned to (i+1)th node. The connections between the nodes are provided in a 2-dimensional array edges[]. The task is to find the maximum path sum between any two nodes. (Both the nodes can be the same also). Note: The path sum is equal to the
9 min read