0

Possible Duplicate:
Stack overflows from deep recursion in Java?

I have written the following method with divide and conquer for my assignment:

calculateC(cMatrix, cMatrix.length - 1, cMatrix.length - 1, w);
    for(int i = cMatrix.length - 2 ;i>=0; i--)
        calculateC(cMatrix, i, i+1, w);

private static double calculateC(double[][] matrix,
    int i,
    int j,
    double[][] w){
    o++;
    double x1 = 0;
    double x2 = 0;
    double result = 0;
    if(i > j) result = 0;
    if(i == j){
        matrix[i][j] = w[i][j];
        result = w[i][j];

    }

    else if(i <= j){

        for(int k = i; k <= j; k++){

            if(i > k - 1)
                x1 = 0;
            else if(i <= k - 1){

                if(matrix[i][k - 1] != 0){
                    x1 = matrix[i][k - 1];
                } else{
                    x1 = calculateC(matrix, i, k - 1, w);

                }
            }
            if(k + 1 > j)
                x2 = 0;
            else if(k + 1 <= j){

                if(matrix[k + 1][j] != 0){
                    x2 = matrix[k + 1][j];

                } else{
                    x2 = calculateC(matrix, k + 1, j, w);
                }
            }

            cs.add(x1 + x2);
            ks.add(k);
        }
        addMin(matrix, i, j, cs, ks, w);
    }

    if(j >= 0 && i >= 0 && j < matrix.length - 1){

        calculateC(matrix, i, j + 1, w);
    }

    return result;

}

This method works on a nn matrix, but for matrixes with n>=10 it causes java.lang.StackOverflowError And it seems to be because of the function calls in this method. I test it for each matrix with n rows and n columns, the recursive method is being called nn times. Is it the reason of exception? How can I solve it? I have written the above method with iterative and it works right but I should write this method with divide and conquer too, I tried hard but I don’t know how to solve the problem.

Community
  • 1
  • 1
Elton.fd
  • 1,575
  • 3
  • 17
  • 24
  • eerily similar code to http://stackoverflow.com/questions/4484874/fill-half-of-a-matrix-with-java And I still don't know what either OP is actually trying to do. – robert_x44 Dec 22 '10 at 16:52

1 Answers1

3

Either:

  1. Increase the stack size of your VM

  2. Rewrite your code so that you make less recursive calls. It doesn't look like it's doing something where you really need to recurse on every cell of the matrix rather than just on matrices of sizes NxN down to 1x1?

  3. Eliminate the recursion entirely. You can rewrite any recursive function with loops and your own stack management.

Dan Grossman
  • 51,866
  • 10
  • 112
  • 101