2014-02-22 47 views
0

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

然而,如果用户在太短的时间间隔连续使用这个工具了几次,它会导致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)); 

     } 

    } 

} 

谢谢

回答

2

编辑:根据由korhner评论(这是完全正确的)。 只添加到堆栈如果颜色是不同的,那么目标的颜色。

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

你必须知道哪些点已经在堆栈中,而不是重新加入的递归的类似的方式。

您可能需要使用额外的数据结构这一点。

+0

所以,如果我要补充一点,已经访问到'Set'的所有像素,并且为了将像素添加到堆栈,看它是否已经存在之前每次检查'Set',你觉得它会解决问题吗? –

+0

试了一下,它解决了这个问题:D简单地做了'Set'存储已经访问过的所有像素,所以我不把它们的副本添加到堆栈中。非常感谢:) –

+1

你不能简单的添加堆叠只有颜色是一样的起始颜色?这样做会更有效率,因为您不需要额外的数据结构。 – korhner