w3resource

Java Exercises: Find possible unique paths from top-left corner to bottom-right corner of a specified grid

Java Basic: Exercise-136 with Solution

Write a Java program to find possible unique paths from top-left corner to bottom-right corner of a given grid (m x n).

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

Sample Solution:

Java Code:

public class Solution {
    /**
     * @param n, m: positive integer (1 <= n ,m <= 100)
     * @return an integer
     */
    public static int unique_Paths(int m, int n) {
        if (m <= 0 || n <= 0) {
            return 0;
        }
        int[][] grid = new int[m][n];
        for (int i = m - 1; i >= 0; --i) {
            for (int j = n - 1; j >= 0; --j) {
                grid[i][j] = get_Paths(grid, i, j);
            }
        }
        return grid[0][0];
    }
    
    private static int get_Paths(int[][] grid, int i, int j) {
        if (i >= grid.length - 1 || j >= grid[0].length - 1) {
            return 1;
        }
        return grid[i][j + 1] + grid[i + 1][j];
    }
    
  public static void main(String[] args) {
		int m = 3;
		int n = 2;
		System.out.println("Unique paths from top-left corner to bottom-right corner of the said grid: "+unique_Paths(m, n));
	}		
} 

Sample Output:

Unique paths from top-left corner to bottom-right corner of the said grid: 3

Flowchart:

Flowchart: Java exercises: Find possible unique paths from top-left corner to bottom-right corner of a given grid.

Java Code Editor:

Company:  Bloomberg

Contribute your code and comments through Disqus.

Previous: Write a Java program to remove duplicates from a sorted linked list.
Next: Write a Java program to find possible unique paths considering some obstacles, from top-left corner to bottom-right corner of a given grid (m x n).

What is the difficulty level of this exercise?



Java: Tips of the Day

Execution of console commands:

Java allows you to execute console commands directly from code using a class Runtime. It is very important not to forget about exception handling.

For example, let's try to open a PDF file through a Java terminal:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
  
public class ShellCommandExec {
  
  public static void main(String[] args) {
    String gnomeOpenCommand = "gnome-open //home//user//Documents//MyDoc.pdf";
  
    try {
      Runtime rt = Runtime.getRuntime();
      Process processObj = rt.exec(gnomeOpenCommand);
  
      InputStream stdin = processObj.getErrorStream();
      InputStreamReader isr = new InputStreamReader(stdin);
      BufferedReader br = new BufferedReader(isr);
  
      String myoutput = "";
  
      while ((myoutput=br.readLine()) != null) {
        myoutput = myoutput+"\n";
      }
      System.out.println(myoutput);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}