@@ -21,10 +21,25 @@ public static int countOfAllPaths(int m, int n) {
2121 if (m == 0 || n == 0 ) {
2222 return 1 ;
2323 }
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)
2528 // if diagonal moment allowed just add + countOfAllPaths(m - 1, n - 1)
2629 }
2730
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+
2843 public static int numberOfPaths (int m , int n ) {
2944 // Create a 2D table to store results of subproblems
3045 int count [][] = new int [m ][n ];
@@ -52,13 +67,21 @@ public static int numberOfPaths(int m, int n) {
5267 }
5368
5469 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 ));
5672 }
5773
5874 public static void main (String [] args ) {
5975 int numberOfRows = 3 ;
6076 int numberOfCols = 3 ;
6177 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 ));
6285 System .out .println (numberOfPaths (numberOfRows , numberOfCols ));
6386 System .out .println (countOfAllPathsFormula (numberOfRows - 1 , numberOfCols - 1 ));
6487 }
0 commit comments