<分区>
我正在编写一个小型绘图应用程序。我正在尝试使用洪水填充算法的非递归实现来制作“桶填充”工具。
但是,如果用户连续多次使用此工具且时间间隔太短,则会导致 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 ) );
}
}
}
谢谢