You are likely recalculating the same cell multiple times. For example, let's say you have a 3x3 grid where all cells are 1. You will calculate count(a, 1, 1)
twice: once as part of count(a, 0, 1)
, and once as part of count(a, 1, 0)
.
You should instead keep track of those values you have calculated so far, and return those where available. For example:
static int count(int a[][], int i, int j) {
return count(a, i, j, new int[a.length][a[0].length]);
}
static int count(int a[][], int i, int j, int[][] results) {
if (results[i][j] != 0) {
return results[i][j];
}
int rows = a.length;
int cols = a[0].length;
int ret;
if(a[i][j] == 0)
ret = 0;
else if (i == rows - 1 && j == cols - 1)
ret = a[i][j];
else if (i == rows - 1)
ret = a[i][j + 1];
else if (j == cols - 1)
ret = a[i + 1][j];
else if (a[i][j] == 1)
ret = count(a, i + 1, j, results) + count(a, i, j + 1, results);
else
ret = 0;
result[i][j]results[i][j] = ret;
return ret;
}