Filling objects with flood fill in java

197 views Asked by At

here is my problem. I created a four-leaf clover and I want to fill him with colour. I have this simple seed_fill (flood_fill):

package projekt;

class SeedFill {        
private int width;
private int height;
private int[] canvas;

public SeedFill(int width, int height, int[] canvas){
    this.width = width;
    this.height = height;
    this.canvas = canvas;
}
public void seed_fill(int x, int y){
    int coord = 3*x + 3*y * width;

    if( x < 0 || y < 0 || x >= width || y >= height)return;

    if(canvas[coord] == 0 && canvas[coord+1] == 255 && canvas[coord+2] == 0)return;

    if(canvas[coord] == 255 && canvas[coord+1] == 255 && canvas[coord+2] == 255)return;

    //colors
    canvas[coord] = 255;
    canvas[coord+1] = 255;
    canvas[coord+2] = 255; 

    //recursive
    seed_fill(x,y-1);
    seed_fill(x,y+1);
    seed_fill(x-1,y);
    seed_fill(x+1,y);
}   
}

The clover is your 400x400 pixels big in total

When I run the project it show me this error message:

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError at lines of code 14, 30 and 31

apparently there is a problem with the recursive, but I'm not that smart to figure it out how to change code to fill that big object.

Thanks for any advices and help.

1

There are 1 answers

0
JB Nizet On

seed_fill() calls seed_fill() for its 4 neighbors, which calls seed_fill() for its 4 neighbors, which calls seed_fill() for its 4 neighbors, which calls seed_fill() for its 4 neighbors, etc.

So you end up with an endless reursive call. For example calling it for (0, 1) calls it for (1, 1), which calls it for (0, 1), which calls it for (1, 1), etc.