-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathLatticePaths.java
More file actions
36 lines (31 loc) · 1.04 KB
/
LatticePaths.java
File metadata and controls
36 lines (31 loc) · 1.04 KB
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
package problem15;
/*
Lattice paths
Problem 15
Starting in the top left corner of a 2×2 grid, and only being able to move to the right
and down, there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
*/
public class LatticePaths {
private static final int GRID_LIMIT = 20;
private static long[][] cache;
public static void main(String[] args) {
cache = new long[GRID_LIMIT + 1][GRID_LIMIT + 1];
System.out.println(findPaths(0, 0));
}
private static long findPaths(int posX, int posY) {
if (posX == GRID_LIMIT && posY == GRID_LIMIT) {
return 1; // new path found
}
if (posX <= GRID_LIMIT && posY <= GRID_LIMIT) {
if (cache[posX][posY] != 0) {
return cache[posX][posY]; // cached result
} else { // recursive backtracking
long paths = findPaths(posX + 1, posY) + findPaths(posX, posY + 1);
cache[posX][posY] = paths;
return paths;
}
}
return 0;
}
}