I have the following objective: "Given two dimensional m by n matrix, write an algorithm to count all possible paths from top left corner to bottom-right corner. You are allowed to move only in two directions, move right OR move down." The problem is quite easy to break down. For example a 3 x 3 grid has as many paths as a 2 x 3 grid and 3 x 2 grid combined. So a recursive solution is quite intuitive.
I have implemented a recursive solution and a solution with memoization (where a 2d-Array stores the paths that are already calculated). In C but somehow, when the grid becomes too large, both function still return the same, but negative solutions (i.e. 15 x 15 works fine, 18 x 18, not anymore). Any idea where this comes from? My code is attached below.
Also.. is there a nice way to code the Array of the Memoization solution? If I use A[m][n] as a function parameter, it doesn't quite work so I just hard-coded it for the moment.
Thanks!
#include <stdio.h>
int gridTravel(int m, int n){
if (m == 0 || n == 0){
return 0;
}
if (m == 1 || n == 1){
return 1;
}
return gridTravel(m-1, n) + gridTravel(m, n-1);
}
int gridTravelMemo(int m, int n, int A[15][15]){
if (m == 0 || n == 0){
return 0;
}
if (m == 1 || n == 1){
return 1;
}
if (A[m-1-1][n-1] == 0){
A[m-1-1][n-1] = gridTravelMemo(m-1, n, A);
}
if (A[m-1][n-1-1] == 0){
A[m-1][n-1-1] = gridTravelMemo(m, n-1, A);
}
return A[m-1-1][n-1] + A[m-1][n-1-1];
}
int main(){
int res = gridTravel(15,15);
printf("There is a total of %d ways to traverse the grid (Grid size is 15 by 15).\n", res);
int res2 = gridTravel(18,18);
printf("There is a total of %d ways to traverse the grid (Grid size is 18 by 18).\n", res2);
int A[15][15] = {0};
int res_memo = gridTravelMemo(15,15,A);
printf("There is a total of %d ways to traverse the grid (Grid size is 15 by 15).\n", res_memo);
return 0;
}