|
| 1 | +import java.time.Instant; |
| 2 | + |
| 3 | +/** |
| 4 | + * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). |
| 5 | + * |
| 6 | + * The robot can only move either down or right at any point in time. |
| 7 | + * The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). |
| 8 | + * |
| 9 | + * How many possible unique paths are there? |
| 10 | + */ |
| 11 | +public class UniquePaths { |
| 12 | + public static void main(String[] args){ |
| 13 | + |
| 14 | + Instant before = Instant.now(); |
| 15 | + int paths = uniquePathsWithMemo(20,10); |
| 16 | + Instant after = Instant.now(); |
| 17 | + System.out.println("Unique paths with memo : " + paths + ", time : " + (after.toEpochMilli() - before.toEpochMilli())); |
| 18 | + |
| 19 | + before = Instant.now(); |
| 20 | + paths = uniquePathsNoMemo(20,10); |
| 21 | + after = Instant.now(); |
| 22 | + System.out.println("Unique paths no memo : " + paths + ", time : " + (after.toEpochMilli() - before.toEpochMilli())); |
| 23 | + |
| 24 | + } |
| 25 | + |
| 26 | + public static int uniquePathsWithMemo(int m, int n) { |
| 27 | + return uniquePathsWithMemo(m,n,0,0,new int[m][n]); |
| 28 | + } |
| 29 | + |
| 30 | + public static int uniquePathsWithMemo(int m, int n, int x, int y, int[][] memo) { |
| 31 | + if(x == m || y == n) return 0; |
| 32 | + if(x == m-1 && y == n-1) return 1; |
| 33 | + if(memo[x][y] != 0) return memo[x][y]; |
| 34 | + memo[x][y] = uniquePathsWithMemo(m,n,x, y+1, memo) + uniquePathsWithMemo(m,n,x + 1, y, memo); |
| 35 | + return memo[x][y]; |
| 36 | + } |
| 37 | + |
| 38 | + public static int uniquePathsNoMemo(int m, int n) { |
| 39 | + return uniquePathsNoMemo(m,n,0,0); |
| 40 | + } |
| 41 | + |
| 42 | + public static int uniquePathsNoMemo(int m, int n, int x, int y) { |
| 43 | + if(x == m || y == n) return 0; |
| 44 | + if(x == m -1 || y == n - 1) return 1; |
| 45 | + return uniquePathsNoMemo(m,n,x, y + 1) + uniquePathsNoMemo(m,n,x + 1, y); |
| 46 | + } |
| 47 | +} |
0 commit comments