Skip to main content

Maximum sum path in a Matrix

Given a matrix of integers, the task is to find a path from the top-left corner to the bottom-right corner of the matrix that maximizes the sum of the elements along the path. The path can only move down or right.

Code Solution

// C Program
// Maximum sum path in a Matrix
#include <stdio.h>
#include <limits.h>

#define R 3 
#define C 4 

// Find the path sum of (0,0) to Matrix (R-1,C-1) 
void path_sum(int matrix[R][C],int *output,int i ,int j,int count,int k,int sum)
{

  if(count==k && *output < sum)
  {
    // When get a new result
    *output = sum;
  }
  else if(i < R && j < C)
  {
    //Recursive execute method with new parameters
    path_sum(matrix,output,i+1,j,count+1,k,sum+matrix[i][j]);
    path_sum(matrix,output,i,j+1,count+1,k,sum+matrix[i][j]);
  }
}

// Handles the request to find max path sum in a matrix
void max_path_sum(int matrix[R][C])
{
    // Set initially min value
    int output = INT_MIN;

    // Calculate max path sum
    path_sum(matrix,&output,0,0,0,R+C-1,0);

    // Display find result
    printf(" %d \n",output);
}

int main()
{
    int matrix[R][C] =
    {
        {4, 6, -2 , 2 },
        {3, -1, 5 , 3 },
        {1, 7,  4,  6 }
    };
    // 4 -> 6 -> -1 -> 7 -> 4 -> 6
    max_path_sum(matrix);

  return 0;
}

Output

 26
/*
    Java program 
    Maximum sum path in a Matrix
*/
// Define TreeNode
public class MyMatrix
{
    public int output;
    // Find the path sum of (0,0) to Matrix (R-1,C-1) 
    public void path_sum(int[][] matrix, 
  	int i, int j, 
  	int count, int k, 
  	int sum, 
  	int rows, int cols)
    {
        if (count == k && this.output < sum)
        {
            // When get a new result
            this.output = sum;
        }
        else if (i < rows && j < cols)
        {
            //Recursive execute method with new parameters
            path_sum(matrix, i + 1, j, count + 1, k, sum + matrix[i][j],rows,cols);
            path_sum(matrix, i, j + 1, count + 1, k, sum + matrix[i][j],rows,cols);
        }
    }
    // Handles the request to find max path sum in a matrix
    public void max_path_sum(int[][] matrix)
    {
        int r = matrix.length;
        int c = matrix[0].length;
        // Set initially min value
        this.output = Integer.MIN_VALUE;
        // Calculate max path sum
        path_sum(matrix, 0, 0, 0, r + c - 1, 0, r, c);
        // Display find result
        System.out.print("  " + this.output + " \n");
    }
    public static void main(String[] args)
    {
        MyMatrix obj = new MyMatrix();
        int[][] matrix =
        {
            {
                4 , 6 , -2 , 2
            }, 
            {
                3 , -1 , 5 , 3
            }, 
            {
                1 , 7 , 4 , 6
            }
        };
        // 4->6->-1->7->4->6
        obj.max_path_sum(matrix);
    }
}

Output

  26
// Include header file
#include <iostream>
#include<limits.h>
#define R 3 
#define C 4 
using namespace std;
/*
    C++ program 
    Maximum sum path in a Matrix
*/
//  Define TreeNode
class MyMatrix
{
	public: int output;
	//  Find the path sum of (0,0) to Matrix (R-1,C-1)
	void path_sum(int matrix[R][C], int i, int j, int count, int k, int sum)
	{
		if (count == k && this->output < sum)
		{
			//  When get a new result
			this->output = sum;
		}
		else if (i < R && j < C)
		{
			// Recursive execute method with new parameters
			this->path_sum(matrix, i + 1, j, count + 1, k, sum + matrix[i][j]);
			this->path_sum(matrix, i, j + 1, count + 1, k, sum + matrix[i][j]);
		}
	}
	//  Handles the request to find max path sum in a matrix
	void max_path_sum(int matrix[R][C])
	{

		//  Set initially min value
		this->output = INT_MIN;
		//  Calculate max path sum
		this->path_sum(matrix, 0, 0, 0, R + C - 1, 0);
		//  Display find result
		cout << "  " << this->output << " \n";
	}
};
int main()
{
	MyMatrix obj = MyMatrix();
	int matrix[R][C] = {
		{
			4 , 6 , -2 , 2
		} , {
			3 , -1 , 5 , 3
		} , {
			1 , 7 , 4 , 6
		}
	};
	//  4->6->-1->7->4->6
	obj.max_path_sum(matrix);
	return 0;
}

Output

  26
// Include namespace system
using System;
/*
    C# program 
    Maximum sum path in a Matrix
*/
//  Define TreeNode
public class MyMatrix
{
	public int output;
	//  Find the path sum of (0,0) to Matrix (R-1,C-1)
	public void path_sum(int[,] matrix, int i, int j, int count, int k, int sum, int rows, int cols)
	{
		if (count == k && this.output < sum)
		{
			//  When get a new result
			this.output = sum;
		}
		else if (i < rows && j < cols)
		{
			// Recursive execute method with new parameters
			path_sum(matrix, i + 1, j, count + 1, k, sum + matrix[i,j], rows, cols);
			path_sum(matrix, i, j + 1, count + 1, k, sum + matrix[i,j], rows, cols);
		}
	}
	//  Handles the request to find max path sum in a matrix
	public void max_path_sum(int[,] matrix)
	{
		int r = matrix.GetLength(0);
		int c = matrix.GetLength(1);
		//  Set initially min value
		this.output = int.MinValue;
		//  Calculate max path sum
		path_sum(matrix, 0, 0, 0, r + c - 1, 0, r, c);
		//  Display find result
		Console.Write("  " + this.output + " \n");
	}
	public static void Main(String[] args)
	{
		MyMatrix obj = new MyMatrix();
		int[,] matrix = {
			{
				4 , 6 , -2 , 2
			} , {
				3 , -1 , 5 , 3
			} , {
				1 , 7 , 4 , 6
			}
		};
		//  4->6->-1->7->4->6
		obj.max_path_sum(matrix);
	}
}

Output

  26
<?php
/*
    Php program 
    Maximum sum path in a Matrix
*/
//  Define TreeNode
class MyMatrix
{
	public $output;
	//  Find the path sum of (0,0) to Matrix (R-1,C-1)
	public	function path_sum( & $matrix, $i, $j, $count, $k, $sum, $rows, $cols)
	{
		if ($count == $k && $this->output < $sum)
		{
			//  When get a new result
			$this->output = $sum;
		}
		else if ($i < $rows && $j < $cols)
		{
			// Recursive execute method with new parameters
			$this->path_sum($matrix, $i + 1, $j, $count + 1, $k, $sum + $matrix[$i][$j], $rows, $cols);
			$this->path_sum($matrix, $i, $j + 1, $count + 1, $k, $sum + $matrix[$i][$j], $rows, $cols);
		}
	}
	//  Handles the request to find max path sum in a matrix
	public	function max_path_sum( & $matrix)
	{
		$r = count($matrix);
		$c = count($matrix[0]);
		//  Set initially min value
		$this->output = -PHP_INT_MAX;
		//  Calculate max path sum
		$this->path_sum($matrix, 0, 0, 0, $r + $c - 1, 0, $r, $c);
		//  Display find result
		echo "  ". $this->output ." \n";
	}
}

function main()
{
	$obj = new MyMatrix();
	$matrix = array(
      array(4, 6, -2, 2), 
      array(3, -1, 5, 3), 
      array(1, 7, 4, 6)
    );
	//  4->6->-1->7->4->6
	$obj->max_path_sum($matrix);
}
main();

Output

  26
/*
    Node Js program 
    Maximum sum path in a Matrix
*/
//  Define TreeNode
class MyMatrix
{
	//  Find the path sum of (0,0) to Matrix (R-1,C-1)
	path_sum(matrix, i, j, count, k, sum, rows, cols)
	{
		if (count == k && this.output < sum)
		{
			//  When get a new result
			this.output = sum;
		}
		else if (i < rows && j < cols)
		{
			// Recursive execute method with new parameters
			this.path_sum(matrix, i + 1, j, count + 1, k, sum + matrix[i][j], rows, cols);
			this.path_sum(matrix, i, j + 1, count + 1, k, sum + matrix[i][j], rows, cols);
		}
	}
	//  Handles the request to find max path sum in a matrix
	max_path_sum(matrix)
	{
		var r = matrix.length;
		var c = matrix[0].length;
		//  Set initially min value
		this.output = -Number.MAX_VALUE;
		//  Calculate max path sum
		this.path_sum(matrix, 0, 0, 0, r + c - 1, 0, r, c);
		//  Display find result
		process.stdout.write("  " + this.output + " \n");
	}
}

function main()
{
	var obj = new MyMatrix();
	var matrix = [
		[4, 6, -2, 2] , [3, -1, 5, 3] , [1, 7, 4, 6]
	];
	//  4->6->-1->7->4->6
	obj.max_path_sum(matrix);
}
main();

Output

  26
import sys

#  Python 3 program 
#  Maximum sum path in a Matrix

#  Define TreeNode
class MyMatrix :
	
	#  Find the path sum of (0,0) to Matrix (R-1,C-1) 
	def path_sum(self, matrix, i, j, count, k, sum, rows, cols) :
		if (count == k and self.output < sum) :
			#  When get a new result
			self.output = sum
		
		elif(i < rows and j < cols) :
			# Recursive execute method with new parameters
			self.path_sum(matrix, i + 1, j, count + 1, k, sum + matrix[i][j], rows, cols)
			self.path_sum(matrix, i, j + 1, count + 1, k, sum + matrix[i][j], rows, cols)
		
	
	#  Handles the request to find max path sum in a matrix
	def max_path_sum(self, matrix) :
		r = len(matrix)
		c = len(matrix[0])
		#  Set initially min value
		self.output = -sys.maxsize
		#  Calculate max path sum
		self.path_sum(matrix, 0, 0, 0, r + c - 1, 0, r, c)
		#  Display find result
		print("  ", self.output ," \n", end = "")
	

def main() :
	obj = MyMatrix()
	matrix = [
		[4, 6, -2, 2] , 
        [3, -1, 5, 3] , 
        [1, 7, 4, 6]
	]
	#  4->6->-1->7->4->6
	obj.max_path_sum(matrix)

if __name__ == "__main__": main()

Output

   26
#  Ruby program 
#  Maximum sum path in a Matrix

#  Define TreeNode
class MyMatrix  
	# Define the accessor and reader of class MyMatrix  
	attr_reader :output
	attr_accessor :output
 
	
	#  Find the path sum of (0,0) to Matrix (R-1,C-1) 
	def path_sum(matrix, i, j, count, k, sum, rows, cols) 
		if (count == k && self.output < sum) 
			#  When get a new result
			self.output = sum
		elsif(i < rows && j < cols) 
			# Recursive execute method with new parameters
			self.path_sum(matrix, i + 1, j, count + 1, k, sum + matrix[i][j], rows, cols)
			self.path_sum(matrix, i, j + 1, count + 1, k, sum + matrix[i][j], rows, cols)
		end

	end

	#  Handles the request to find max path sum in a matrix
	def max_path_sum(matrix) 
		r = matrix.length
		c = matrix[0].length
		#  Set initially min value
		self.output = -(2 ** (0. size * 8 - 2))
		#  Calculate max path sum
		self.path_sum(matrix, 0, 0, 0, r + c - 1, 0, r, c)
		#  Display find result
		print("  ", self.output ," \n")
	end

end

def main() 
	obj = MyMatrix.new()
	matrix = [
		[4, 6, -2, 2] , 
        [3, -1, 5, 3] , 
        [1, 7, 4, 6]
	]
	#  4->6->-1->7->4->6
	obj.max_path_sum(matrix)
end

main()

Output

  26 
/*
    Scala program 
    Maximum sum path in a Matrix
*/
//  Define TreeNode
class MyMatrix(var output: Int)
{
	//  Find the path sum of (0,0) to Matrix (R-1,C-1)
	def path_sum(matrix: Array[Array[Int]], 
      i: Int, j: Int, count: Int, k: Int, 
        sum: Int, rows: Int, cols: Int): Unit = {
		if (count == k && this.output < sum)
		{
			//  When get a new result
			this.output = sum;
		}
		else if (i < rows && j < cols)
		{
			// Recursive execute method with new parameters
			this.path_sum(matrix, i + 1, j, count + 1, k, sum + matrix(i)(j), rows, cols);
			this.path_sum(matrix, i, j + 1, count + 1, k, sum + matrix(i)(j), rows, cols);
		}
	}
	//  Handles the request to find max path sum in a matrix
	def max_path_sum(matrix: Array[Array[Int]]): Unit = {
		var r: Int = matrix.length;
		var c: Int = matrix(0).length;
		//  Set initially min value
		this.output = Int.MinValue;
		//  Calculate max path sum
		this.path_sum(matrix, 0, 0, 0, r + c - 1, 0, r, c);
		//  Display find result
		print("  " + this.output + " \n");
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var obj: MyMatrix = new MyMatrix(0);
		var matrix: Array[Array[Int]] = 
          Array(Array(4, 6, -2, 2), 
                Array(3, -1, 5, 3), 
                Array(1, 7, 4, 6));
		//  4->6->-1->7->4->6
		obj.max_path_sum(matrix);
	}
}

Output

  26
/*
    Swift 4 program 
    Maximum sum path in a Matrix
*/
//  Define TreeNode
class MyMatrix
{
	var output: Int;
	init()
	{
		self.output = 0;
	}
	//  Find the path sum of (0,0) to Matrix (R-1,C-1)
	func path_sum(_ matrix: [[Int]], _ i: Int, _ j: Int, _ count: Int, _ k: Int, _ sum: Int, _ rows: Int, _ cols: Int)
	{
		if (count == k && self.output < sum)
		{
			//  When get a new result
			self.output = sum;
		}
		else if (i < rows && j < cols)
		{
			// Recursive execute method with new parameters
			self.path_sum(matrix, i + 1, j, count + 1, k, sum + matrix[i][j], rows, cols);
			self.path_sum(matrix, i, j + 1, count + 1, k, sum + matrix[i][j], rows, cols);
		}
	}
	//  Handles the request to find max path sum in a matrix
	func max_path_sum(_ matrix: [
		[Int]
	])
	{
		let r: Int = matrix.count;
		let c: Int = matrix[0].count;
		//  Set initially min value
		self.output = Int.min;
		//  Calculate max path sum
		self.path_sum(matrix, 0, 0, 0, r + c - 1, 0, r, c);
		//  Display find result
		print("  ", self.output ," \n", terminator: "");
	}
}
func main()
{
	let obj: MyMatrix = MyMatrix();
	let matrix: [
		[Int]
	] = [
		[4, 6, -2, 2] , [3, -1, 5, 3] , [1, 7, 4, 6]
	];
	//  4->6->-1->7->4->6
	obj.max_path_sum(matrix);
}
main();

Output

   26
/*
    Kotlin program 
    Maximum sum path in a Matrix
*/
//  Define TreeNode
class MyMatrix
{
	var output: Int;
	constructor()
	{
		this.output = 0;
	}
	//  Find the path sum of (0,0) to Matrix (R-1,C-1)
	fun path_sum(matrix: Array < Array < Int >> , i: Int, j: Int, count: Int, k: Int, sum: Int, rows: Int, cols: Int): Unit
	{
		if (count == k && this.output < sum)
		{
			//  When get a new result
			this.output = sum;
		}
		else if (i < rows && j < cols)
		{
			// Recursive execute method with new parameters
			this.path_sum(matrix, i + 1, j, count + 1, k, sum + matrix[i][j], rows, cols);
			this.path_sum(matrix, i, j + 1, count + 1, k, sum + matrix[i][j], rows, cols);
		}
	}
	//  Handles the request to find max path sum in a matrix
	fun max_path_sum(matrix: Array<Array<Int>> ): Unit
	{
		var r: Int = matrix.count();
		var c: Int = matrix[0].count();
		//  Set initially min value
		this.output = Int.MIN_VALUE;
		//  Calculate max path sum
		this.path_sum(matrix, 0, 0, 0, r + c - 1, 0, r, c);
		//  Display find result
		print("  " + this.output + " \n");
	}
}
fun main(args: Array < String > ): Unit
{
	var obj: MyMatrix = MyMatrix();
	var matrix: Array <Array<Int>> = 
      arrayOf(arrayOf(4, 6, -2, 2), 
              arrayOf(3, -1, 5, 3), 
              arrayOf(1, 7, 4, 6));
	//  4->6->-1->7->4->6
	obj.max_path_sum(matrix);
}

Output

  26




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment