Java 非递归泛洪填充算法导致OutOfMemory错误

Java 非递归泛洪填充算法导致OutOfMemory错误,java,algorithm,out-of-memory,flood-fill,Java,Algorithm,Out Of Memory,Flood Fill,我正在写一个小的绘图应用程序。我正在尝试使用洪水填充算法的非递归实现来制作一个“桶填充”工具 但是,如果用户连续几次使用此工具且时间间隔太短,则会在Java中导致OutOfMemoryError 我想知道如何优化我的实现,以避免出现此错误 public void floodFill(int x, int y, Color targetColor, Color replacementColor) { LinkedList<Point> stack = new LinkedLi

我正在写一个小的绘图应用程序。我正在尝试使用洪水填充算法的非递归实现来制作一个“桶填充”工具

但是,如果用户连续几次使用此工具且时间间隔太短,则会在Java中导致
OutOfMemoryError

我想知道如何优化我的实现,以避免出现此错误

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 ) );

        }

    }

}
public void泛光填充(int x,int y,Color targetColor,Color replacementColor){
LinkedList堆栈=新建LinkedList();
stack.add(新点(x,y));//添加单击鼠标的点。
点温;
而(!stack.isEmpty()){
temp=stack.pop();
int pixelColorRGB=drawingArea.getRGB((int)temp.getX(),(int)temp.getY());
颜色pixelColor=新颜色(pixelColorRGB,真);
if(像素颜色等于(目标颜色)){
g、 setColor(replacementColor);
g、 fillRect((int)temp.getX(),(int)temp.getY(),1,1);
if(此.contains((int)temp.getX()-1,(int)temp.getY()))
添加(新点((int)temp.getX()-1,(int)temp.getY());
如果(此参数包含((int)temp.getX()+1,(int)temp.getY()))
添加(新点((int)temp.getX()+1,(int)temp.getY());
if(此参数包含((int)temp.getX(),(int)temp.getY()-1))
添加(新点((int)temp.getX(),(int)temp.getY()-1));
if(此参数包含((int)temp.getX(),(int)temp.getY()+1))
添加(新点((int)temp.getX(),(int)temp.getY()+1));
}
}
}

谢谢

编辑:根据科纳的评论(完全正确)。 仅当颜色与目标颜色不同时才添加到堆栈

原职: 将屏幕上的所有像素添加到堆栈应该可以。 我想问题可能是你有重叠的点

与递归解决方案类似,您必须知道堆栈中已经存在哪个点,并且不要再添加它


为此,您可能需要使用其他数据结构。

因此,如果我将已访问的所有像素添加到
集合
中,并在每次向堆栈添加像素之前检查
集合
,以查看它是否已经存在,您认为这会解决问题吗?尝试过,它解决了这个问题:D简单地做了一个
集合
来存储所有已经访问过的像素,所以我不会将它们的重复项添加到堆栈中。非常感谢:)如果颜色与起始颜色相同,您不能简单地添加到堆栈吗?这样会更加高效,因为您不需要额外的数据结构。