Search code examples
javarecursionminesweeper

How to properly use recursion in this function?


ok, i have this function that needs to use recursion, to search in a mineswepper(int[][] m) given a coordinate(i, j) by the user, a zero. The zero means there is no mines near that localition. If it is a zero, then my function should show this zero and the zeros around this initial zero in a range of one localition. This has to be made in a recursive way, for all the zeros found.

My int[][]v is my vision matrix, it used to give and status(1 => you can show the location, 0 => keep the ?) for all the locations individually, so when i print all the matrix m we can only see the locations that have a 1 in the matrix v.

1-. Found a zero2

2-. Search around to find other zeros, until there is no more zero to found

?   ?   ?   ?
?   ?   ?   ?
?   ?   0   ?
?   ?   ?   ?
?   ?   ?   ?

how it would look like in the vision matrix v

0   0   0   0
0   0   0   0
0   0   1   0
0   0   0   0
0   0   0   0



?   ?   ?   ?
?   ?   ?   ?
?   ?   0   ?
?   ?   ?   0
?   ?   ?   ?

how it would look like in the vision matrix v

0   0   0   0
0   0   0   0
0   0   1   0
0   0   0   1
0   0   0   0

 public void zeros(int[][]m, int[][]v, int j, int i){

            v[i][j] = 1;

            for(int a = Math.max(0, i-1); a < Math.min(5,i+2); a++){
              for(int b = Math.max(0,j-1); b < Math.min(5,j+2); b++){
                 if(m[a][b] == 0){
                     i = a;
                     j = b;
                    zeros( m, v, i, j);}

                }
            }         
   }

The fors are to searh in all the locations around the given i and j.

It shows me errors, Exception in thread "main" java.lang.StackOverflowError. I dont get it why. Maybe someone could give a way eary to make the recursivity, or tell me my mistake.


Solution

  • so far all good. but fix the following

    remove those two lines:

    i = a;
    j = b;
    

    call it as follow:

    zeros( m, v, a, b);
    

    instead of:

    zeros( m, v, i, j);
    

    also change this:

    public void zeros(int[][]m, int[][]v, int j, int i)
    

    too:

    public void zeros(int[][]m, int[][]v, int i, int j)
    

    do this to:

    if(m[a][b] == 0 && v[a][b]==0)