/
UniquePaths.java
38 lines (31 loc) · 1.27 KB
/
UniquePaths.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.hrishikeshmishra.practices.dynamicprogramming;
import static com.hrishikeshmishra.practices.dynamicprogramming.UniquePaths.uniquePathsByBacktracking;
/**
* Problem:
* Unique Paths
* A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).
* The robot can only move either down or right at any point in time.
* The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
* How many possible unique paths are there?
*
* @author hrishikesh.mishra
* @video https://www.youtube.com/watch?v=GO5QHC_BmvM
* @link http://hrishikeshmishra.com/unique-paths/
*/
public class UniquePaths {
public static int uniquePathsByBacktracking(int row, int col, int lastRow, int lastCol) {
if (row == lastRow && col == lastCol) {
return 1;
}
if (row > lastRow || col > lastCol) {
return 0;
}
return uniquePathsByBacktracking(row + 1, col, lastRow, lastCol) +
uniquePathsByBacktracking(row, col + 1, lastRow, lastCol);
}
}
class UniquePathsTest {
public static void main(String[] args) {
System.out.println("Unique paths by backtracking 4X4 grid: " + uniquePathsByBacktracking(0, 0, 3, 3));
}
}