I need some help with this problem. I have to sum all integers in a 2d array using recursion. Below is what I have managed to do on my own, but I'm stuck. This code generates the sum 14, which should be 18.
public class tablerecursion {
public static void main(String[] args) {
int[][] tabell = new int[][] { { 1, 2, 3 }, { 3, 2, 1 }, { 1, 2, 3 } };
int sum = rec(tabell, 2, 2);
System.out.println(sum);
}
static int rec(int[][] table, int n, int m) {
if (m == 0)
return table[n][0];
if (n == 0)
return table[0][m];
System.out.println("n:" + n + " m:" + m);
return rec(table, n - 1, m) + rec(table, n, m - 1);
}
}
Any suggestions? Is the base case wrong? Or is the recursive method wrong?