2014-02-22 45 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