I'm writing a small drawing application. I'm trying to make a 'bucket fill' tool using a non-recursive implementation of the flood-fill algorithm.

However, if the user uses this tool a few times in a row with too short time intervals, it causes an OutOfMemoryError in Java.

I would like to know how I can optimize my implementation so this error won't occur.

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

    LinkedList<Point> stack = new LinkedList<Point>();

    stack.add(new Point(x,y)); // adding the point where the mouse was clicked.

    Point temp;
    while( !stack.isEmpty() ){

        temp = stack.pop();

        int pixelColorRGB = drawingArea.getRGB( (int)temp.getX(), (int)temp.getY() );
        Color pixelColor = new Color(pixelColorRGB, true);

        if(pixelColor.equals(targetColor)){

            g.setColor(replacementColor);
            g.fillRect((int)temp.getX(), (int)temp.getY(), 1, 1);

            if(this.contains((int) temp.getX() - 1, (int) temp.getY()))
                stack.add( new Point( (int) temp.getX() - 1, (int) temp.getY() ) );

            if(this.contains((int) temp.getX() + 1, (int) temp.getY()))
                stack.add( new Point( (int) temp.getX() + 1, (int) temp.getY() ) );

            if(this.contains((int) temp.getX(), (int) temp.getY() - 1))
                stack.add( new Point( (int) temp.getX(), (int) temp.getY() - 1 ) );

            if(this.contains((int) temp.getX(), (int) temp.getY() + 1))
                stack.add( new Point( (int) temp.getX(), (int) temp.getY() + 1 ) );

        }

    }

}

Thank you

有帮助吗?

解决方案

edit: according to comment by korhner (which is totally right). only add to stack if the color is different then target color.

original post: Adding all pixels on screen to the stack should be fine. I think the problem might be you have overlapping points.

In a similar way of a recursive solution you must know which point is already in the stack and not adding it again.

You might need to use additional data structure for that.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top