@@ -21,10 +21,25 @@ public static int countOfAllPaths(int m, int n) {
21
21
if (m == 0 || n == 0 ) {
22
22
return 1 ;
23
23
}
24
- return countOfAllPaths (m - 1 , n ) + countOfAllPaths (m , n - 1 );
24
+ int x = countOfAllPaths (m - 1 , n );
25
+ int y = countOfAllPaths (m , n - 1 );
26
+ return x + y ;
27
+ // int z = countOfAllPaths(m - 1, n - 1)
25
28
// if diagonal moment allowed just add + countOfAllPaths(m - 1, n - 1)
26
29
}
27
30
31
+ public static int countOfAllPathsStartFromTopLeft (int m , int n ) {
32
+ int i = 0 , j = 0 ;
33
+ return countOfAllPathsFromTopLeft (m , n , i , j );
34
+ }
35
+
36
+ private static int countOfAllPathsFromTopLeft (int m , int n , int i , int j ) {
37
+ if (i == m || j == n ) {
38
+ return 1 ;
39
+ }
40
+ return countOfAllPathsFromTopLeft (m , n , i + 1 , j ) + countOfAllPathsFromTopLeft (m , n , i , j + 1 );
41
+ }
42
+
28
43
public static int numberOfPaths (int m , int n ) {
29
44
// Create a 2D table to store results of subproblems
30
45
int count [][] = new int [m ][n ];
@@ -52,13 +67,21 @@ public static int numberOfPaths(int m, int n) {
52
67
}
53
68
54
69
public static long countOfAllPathsFormula (int m , int n ) {
55
- return (Factorial .findFactorial (m + n )) / (Factorial .findFactorial (m ) * Factorial .findFactorial (n ));
70
+ return (Factorial .findFactorial (m + n )) /
71
+ (Factorial .findFactorial (m ) * Factorial .findFactorial (n ));
56
72
}
57
73
58
74
public static void main (String [] args ) {
59
75
int numberOfRows = 3 ;
60
76
int numberOfCols = 3 ;
61
77
System .out .println (countOfAllPaths (numberOfRows - 1 , numberOfCols - 1 ));
78
+ System .out .println (countOfAllPathsStartFromTopLeft (numberOfRows - 1 , numberOfCols - 1 ));
79
+ System .out .println (numberOfPaths (numberOfRows , numberOfCols ));
80
+ System .out .println (countOfAllPathsFormula (numberOfRows - 1 , numberOfCols - 1 ));
81
+ numberOfRows = 4 ;
82
+ numberOfCols = 4 ;
83
+ System .out .println (countOfAllPaths (numberOfRows - 1 , numberOfCols - 1 ));
84
+ System .out .println (countOfAllPathsStartFromTopLeft (numberOfRows - 1 , numberOfCols - 1 ));
62
85
System .out .println (numberOfPaths (numberOfRows , numberOfCols ));
63
86
System .out .println (countOfAllPathsFormula (numberOfRows - 1 , numberOfCols - 1 ));
64
87
}
0 commit comments