Find Minimum Path Sum in a given 2D Array.
💻 coding

Find Minimum Path Sum in a given 2D Array.

1 min read 144 words
1 min read
ShareWhatsAppPost on X
  • 1The problem involves finding a minimum path sum in a 2D grid filled with non-negative numbers.
  • 2You can only move down or right to minimize the sum of the path.
  • 3Dynamic programming is used to calculate the minimum path sum efficiently.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem involves finding a minimum path sum in a 2D grid filled with non-negative numbers."

Find Minimum Path Sum in a given 2D Array.

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

Input:
[
 [1,3,1],
 [1,5,1],
 [4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.

We will Solve this problem using dynamic programming

public class MinimumPathSum {

	public static void main(String[] args) {
		int[][] arr = new int[][] {{1,3,1},
		 {1,5,1},
		 {4,2,1}};
		 
		System.out.println(CalculateMinimumPathSum(arr));

	}

	private static int CalculateMinimumPathSum(int[][] arr) {
		for(int i=0;i<3;i++) {
			for(int j=0;j<3;j++) {
				if(i==0 && j == 0)
					continue;
				else if(i==0)
					arr[i][j] = arr[i][j] + arr[i][j-1];
				else if(j==0)
					arr[i][j] = arr[i][j] + arr[i-1][j];
				else
					arr[i][j] = min(arr[i-1][j]+arr[i][j], arr[i][j-1]+arr[i][j]);
				
					
			}
		}
		return arr[2][2];
	}

	private static int min(int i, int j) {
		return i<j?i:j;
	}

}

Output :

7

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 20 July 2018 · 1 min read · 144 words

Part of AskGif Blog · coding

You might also like

Find Minimum Path Sum in a given 2D Array. | AskGif Blog