-
Notifications
You must be signed in to change notification settings - Fork 0
/
GridTraveller.java
42 lines (37 loc) · 1.48 KB
/
GridTraveller.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
39
40
41
42
package com.srihari.practice.dp;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
public class GridTraveller {
public BigInteger findNumberOfPathsRecursive(int rows, int columns) {
if(rows == 0 || columns == 0) {
return BigInteger.ZERO;
} else if(rows == 1 && columns == 1) {
return BigInteger.ONE;
} else {
BigInteger right = findNumberOfPathsRecursive(rows, columns-1);
BigInteger down = findNumberOfPathsRecursive(rows-1, columns);
return right.add(down);
}
}
private BigInteger findNumberOfPathsMemoized(int rows, int columns, Map<String, BigInteger> memo) {
String memoKey = String.format("%d,%d", rows, columns);
if(rows == 0 || columns == 0) {
return BigInteger.ZERO;
} else if(rows == 1 && columns == 1) {
return BigInteger.ONE;
} else if(memo.containsKey(memoKey)) {
return memo.get(memoKey);
} else {
BigInteger right = findNumberOfPathsMemoized(rows, columns-1, memo);
BigInteger down = findNumberOfPathsMemoized(rows-1, columns, memo);
BigInteger result = right.add(down);
memo.put(memoKey, result);
return result;
}
}
public BigInteger findNumberOfPathsMemoized(int rows, int columns) {
Map<String, BigInteger> memo = new HashMap<>();
return findNumberOfPathsMemoized(rows, columns, memo);
}
}