非递归泛洪填充算法会导致内存不足错误



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

但是,如果用户以太短的时间间隔连续使用此工具几次,则会导致 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 ) );
        }
    }
}

谢谢

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

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

以与递归解决方案类似的方式,您必须知道堆栈中已经存在哪个点,而不是再次添加它。

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

最新更新