1
1
package com .thealgorithms .dynamicprogramming ;
2
2
3
- /*
4
- * this is an important Algo in which
5
- * we have starting and ending of board and we have to reach
6
- * we have to count no. of ways
7
- * that help to reach end point i.e number by rolling dice
8
- * which have 1 to 6 digits
9
-
10
- Test Case:
11
- here target is 10
12
-
13
- int n=10;
14
- startAlgo();
15
- System.out.println(bpR(0,n));
16
- System.out.println(endAlgo()+"ms");
17
- int[] strg=new int [n+1];
18
- startAlgo();
19
- System.out.println(bpRS(0,n,strg));
20
- System.out.println(endAlgo()+"ms");
21
- startAlgo();
22
- System.out.println(bpIS(0,n,strg));
23
- System.out.println(endAlgo()+"ms");
24
-
25
-
26
-
27
- */
28
3
public final class BoardPath {
29
4
private BoardPath () {
30
5
}
31
6
32
- public static long startTime ;
33
- public static long endTime ;
34
-
35
- public static void startAlgo () {
36
- startTime = System .currentTimeMillis ();
37
- }
38
-
39
- public static long endAlgo () {
40
- endTime = System .currentTimeMillis ();
41
- return endTime - startTime ;
42
- }
43
-
7
+ /**
8
+ * Recursive solution without memoization
9
+ *
10
+ * @param start - the current position
11
+ * @param end - the target position
12
+ * @return the number of ways to reach the end from the start
13
+ */
44
14
public static int bpR (int start , int end ) {
45
15
if (start == end ) {
46
16
return 1 ;
@@ -54,6 +24,14 @@ public static int bpR(int start, int end) {
54
24
return count ;
55
25
}
56
26
27
+ /**
28
+ * Recursive solution with memoization
29
+ *
30
+ * @param curr - the current position
31
+ * @param end - the target position
32
+ * @param strg - memoization array
33
+ * @return the number of ways to reach the end from the start
34
+ */
57
35
public static int bpRS (int curr , int end , int [] strg ) {
58
36
if (curr == end ) {
59
37
return 1 ;
@@ -71,15 +49,23 @@ public static int bpRS(int curr, int end, int[] strg) {
71
49
return count ;
72
50
}
73
51
52
+ /**
53
+ * Iterative solution with tabulation
54
+ *
55
+ * @param curr - the current position (always starts from 0)
56
+ * @param end - the target position
57
+ * @param strg - memoization array
58
+ * @return the number of ways to reach the end from the start
59
+ */
74
60
public static int bpIS (int curr , int end , int [] strg ) {
75
61
strg [end ] = 1 ;
76
62
for (int i = end - 1 ; i >= 0 ; i --) {
77
63
int count = 0 ;
78
- for (int dice = 1 ; dice <= 6 && dice + i < strg . length ; dice ++) {
64
+ for (int dice = 1 ; dice <= 6 && dice + i <= end ; dice ++) {
79
65
count += strg [i + dice ];
80
66
}
81
67
strg [i ] = count ;
82
68
}
83
- return strg [0 ];
69
+ return strg [curr ];
84
70
}
85
71
}
0 commit comments