11package com .thealgorithms .dynamicprogramming ;
22
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- */
283public final class BoardPath {
294 private BoardPath () {
305 }
316
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+ */
4414 public static int bpR (int start , int end ) {
4515 if (start == end ) {
4616 return 1 ;
@@ -54,6 +24,14 @@ public static int bpR(int start, int end) {
5424 return count ;
5525 }
5626
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+ */
5735 public static int bpRS (int curr , int end , int [] strg ) {
5836 if (curr == end ) {
5937 return 1 ;
@@ -71,15 +49,23 @@ public static int bpRS(int curr, int end, int[] strg) {
7149 return count ;
7250 }
7351
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+ */
7460 public static int bpIS (int curr , int end , int [] strg ) {
7561 strg [end ] = 1 ;
7662 for (int i = end - 1 ; i >= 0 ; i --) {
7763 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 ++) {
7965 count += strg [i + dice ];
8066 }
8167 strg [i ] = count ;
8268 }
83- return strg [0 ];
69+ return strg [curr ];
8470 }
8571}
0 commit comments