java - 非递归 Flood-Fill 算法导致 OutOfMemoryError

标签 java algorithm out-of-memory flood-fill

<分区>

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

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

我想知道如何优化我的实现,以免发生此错误。

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 的评论(完全正确)。 仅当颜色与目标颜色不同时才添加到堆栈。

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

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

您可能需要为此使用额外的数据结构。

关于java - 非递归 Flood-Fill 算法导致 OutOfMemoryError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21954746/

相关文章:

java - 应用程序空指针异常

查找满足一组条件的数字序列的算法

c# - 计算列表的每个元素出现在多少个连续的子列表中

c - 在 malloc 中使用 sizeof(void)

java.lang.OutOfMemoryError : Java heap space to find all strings of length n 错误

c++ - 如何读取文件或流直到找到字符串

java - 如何使用 JNDI 将 Java 应用程序连接到数据库?

java - Windows XP 阻止我的程序创建的 zip 文件

java - 带有 java -jar 和 Tomcat 8 的 spring boot getVirtualServerName。STS 运行良好

algorithm - 我怎样才能增加这个PRNG的周期?