Aviv Cohn
Aviv Cohn

Reputation: 17193

Flood Fill algorithm causes StackOverFlowError

I am programming a simple paint application using Java. I'm trying to use a recursive implementation of the Flood Fill algorithm as my 'bucket fill' tool.

However, this always gives me a StackOverFlowError. (No matter how small the area that I'm using the 'bucket fill tool' on is).

EDIT: Changed the code to make it more efficient. Still same error.

Here's the code:

public void floodFill(int x, int y, Color targetColor, Color replacementColor) throws AWTException{

    pixelColor = robot.getPixelColor(x,y);

    g.setColor(replacementColor);
    g.fillRect(x, y, 1, 1);

    if(robot.getPixelColor(x-1, y).equals(targetColor))
        floodFill(x-1, y, targetColor, replacementColor);

    if(robot.getPixelColor(x+1, y).equals(targetColor))
        floodFill(x+1, y, targetColor, replacementColor);

    if(robot.getPixelColor(x, y-1).equals(targetColor))
        floodFill(x, y-1, targetColor, replacementColor);

    if(robot.getPixelColor(x, y+1).equals(targetColor))
        floodFill(x, y+1, targetColor, replacementColor);

}

I would like to know if there is a way to still use recursion with this algorithm, and not get this error.

If not, what possible non-recursive implementations of this algorithm are there, that I can use in my program?

Upvotes: 4

Views: 1793

Answers (3)

David Medenjak
David Medenjak

Reputation: 34532

Just check at the beginning of the function the current Position, which color it has.

If it already has the replacementColor you already visited this point and can return.

public void floodFill(int x, int y, Color targetColor, Color replacementColor) throws AWTException{
{
  if(robot.getPixelColor(x, y).equals(replacementColor))
    return;
...
}

Upvotes: 1

Sandeep
Sandeep

Reputation: 1

A much better way to implement bucket fill is to figure out which figure or area contains the mouse click position. (e.g) if you click inside a circle(with no other objects), then you want to fill up the circle. So if you maintain some kind of area map you can quickly figure out in which area the mouse click position is and fill up that area using existing methods (from some standard Java or external software) to fill up an area with colour.

Upvotes: 0

Smutje
Smutje

Reputation: 18133

You additionally have to check for the already set target color, otherwise you overwrite the same target color again and again.

Upvotes: 1

Related Questions