- Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathBoardPath.java
71 lines (67 loc) · 1.92 KB
/
BoardPath.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
packagecom.thealgorithms.dynamicprogramming;
publicfinalclassBoardPath {
privateBoardPath() {
}
/**
* Recursive solution without memoization
*
* @param start - the current position
* @param end - the target position
* @return the number of ways to reach the end from the start
*/
publicstaticintbpR(intstart, intend) {
if (start == end) {
return1;
} elseif (start > end) {
return0;
}
intcount = 0;
for (intdice = 1; dice <= 6; dice++) {
count += bpR(start + dice, end);
}
returncount;
}
/**
* Recursive solution with memoization
*
* @param curr - the current position
* @param end - the target position
* @param strg - memoization array
* @return the number of ways to reach the end from the start
*/
publicstaticintbpRS(intcurr, intend, int[] strg) {
if (curr == end) {
return1;
} elseif (curr > end) {
return0;
}
if (strg[curr] != 0) {
returnstrg[curr];
}
intcount = 0;
for (intdice = 1; dice <= 6; dice++) {
count += bpRS(curr + dice, end, strg);
}
strg[curr] = count;
returncount;
}
/**
* Iterative solution with tabulation
*
* @param curr - the current position (always starts from 0)
* @param end - the target position
* @param strg - memoization array
* @return the number of ways to reach the end from the start
*/
publicstaticintbpIS(intcurr, intend, int[] strg) {
strg[end] = 1;
for (inti = end - 1; i >= 0; i--) {
intcount = 0;
for (intdice = 1; dice <= 6 && dice + i <= end; dice++) {
count += strg[i + dice];
}
strg[i] = count;
}
returnstrg[curr];
}
}