# Java Exercises: Find a path from top left to bottom in right direction

## Java Basic: Exercise-133 with Solution

Write a Java program to find a path from top left to bottom in right direction which minimizes the sum of all numbers along its path.

Note: Move either down or right at any point in time.

**Pictorial Presentation:**

**Sample Solution:**

**Java Code:**

```
public class Solution {
public static int minPathSum(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) {
return 0;
}
int m = grid.length;
int n = grid[0].length;
int[][] temp = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
temp[i][j] = grid[i][j];
continue;
}
// Compute temp
int from_up = i == 0 ? Integer.MAX_VALUE : temp[i - 1][j];
int from_left = j == 0 ? Integer.MAX_VALUE : temp[i][j - 1];
temp[i][j] = Math.min(from_up, from_left) + grid[i][j];
}
}
return temp[m - 1][n - 1];
}
/* Driver program to test above functions */
public static void main(String[] args) {
int[][] grid = new int[][] {{7,4,2},
{0,5,6},
{3,1,2}};
System.out.println("Sum of all numbers along its path: "+minPathSum(grid));
}
}
```

Sample Output:

Sum of all numbers along its path: 13

**Flowchart: **

**Java Code Editor:**

** Contribute your code and comments through Disqus.**

**Previous:**Write a Java program to find the new length of a given sorted array where duplicate elements appeared at most twice.

**Next:** Write a Java program to find the distinct ways you can climb to the top (n steps to reach to the top) of stairs. Each time you can either climb 1 or 2 steps.

**What is the difficulty level of this exercise?**

Test your Programming skills with w3resource's quiz.

## Java: Tips of the Day

** countOccurrences**

Counts the occurrences of a value in an array.

Use Arrays.stream().filter().count() to count total number of values that equals the specified value.

public static long countOccurrences(int[] numbers, int value) { return Arrays.stream(numbers) .filter(number -> number == value) .count(); }

Ref: https://bit.ly/3kCAgLb

**Exercises: Weekly Top 12 Most Popular Topics**- Pandas DataFrame: Exercises, Practice, Solution
- Conversion Tools
- JavaScript: HTML Form Validation
- SQL Exercises, Practice, Solution - SUBQUERIES
- C Programming Exercises, Practice, Solution : For Loop
- Python Exercises, Practice, Solution
- Python Data Type: List - Exercises, Practice, Solution
- C++ Basic: Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - exercises on Employee Database
- SQL Exercises, Practice, Solution - exercises on Movie Database
- SQL Exercises, Practice, Solution - exercises on Soccer Database
- C Programming Exercises, Practice, Solution : Recursion