Stackoverflowerror when trying to call recursive method

Asked

Viewed 44 times

0

I’m developing an image editor Paint, and I can’t do the paint bucket method, the idea is: (example)

I have an 8x8 matrix and the possible values in this example are "-", "X" or "O"

   0  1  2  3  4  5  6  7
0 [-][-][-][-][-][-][-][x]
1 [-][-][-][-][-][-][x][-]
2 [-][-][-][-][-][x][-][-]
3 [-][-][-][-][x][-][-][-]
4 [-][-][-][-][x][-][-][-]
5 [-][-][x][x][-][-][-][-]
6 [-][x][-][-][-][-][-][-]
7 [x][-][-][-][-][-][-][-]

in my method I choose a field that has a "-", then he and all the pampos of the sides or above or below that are "-", become "O" and this is a recursive method, example: paints(5,6);

   0  1  2  3  4  5  6  7
0 [-][-][-][-][-][-][-][x]
1 [-][-][-][-][-][-][x][o]
2 [-][-][-][-][-][x][o][o]
3 [-][-][-][-][x][o][o][o]
4 [-][-][-][-][x][o][o][o]
5 [-][-][x][x][o][o][o][o]
6 [-][x][o][o][o][o][o][o]
7 [x][o][o][o][o][o][o][o]

my code implementing in a bufferedImage instead of a matrix:

public static void pinta(BufferedImage buff,int x,int y,int color)
{
        int filtro=buff.getRGB(x,y);
        buff.setRGB(x,y,color);
        if(filtro!=color){
            if(buff.getRGB(x+1, y)==filtro){
                pinta(buff,x+1,y,color);
            }
            if(buff.getRGB(x-1, y)==filtro){
                pinta(buff,x-1,y,color);
            }
            if(buff.getRGB(x, y+1)==filtro){
                pinta(buff,x,y+1,color);
            }
            if(buff.getRGB(x, y-1)==filtro){
                pinta(buff,x,y-1,color);
            }
        }
    }

this code works for the example of the matrix because it is very small, but when I try in a large image, larger than 200px for 200px more or less, he StackOverflowError, it has nothing to do with the fact that I have not put a condition to avoid the CordenatesOffBoundException, whereas this will not happen in my example to facilitate. So how do I do this method without using recursion? can someone give me an example of code?

  • In general, stack overflow is caused when the memory dedicated to the program is filled with function calls. One output is you process the data in batches - in parts.

  • 1

    So don’t use recursion.

  • Could provide error log?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.