2014-11-22 204 views
0

這是我的問題。我製作了四葉三葉草,我想用顏色填充他。 我有這個簡單的seed_fill(flood_fill):用java填充洪水填充對象

package projekt; 

class SeedFill {   
private int width; 
private int height; 
private int[] canvas; 

public SeedFill(int width, int height, int[] canvas){ 
    this.width = width; 
    this.height = height; 
    this.canvas = canvas; 
} 
public void seed_fill(int x, int y){ 
    int coord = 3*x + 3*y * width; 

    if(x < 0 || y < 0 || x >= width || y >= height)return; 

    if(canvas[coord] == 0 && canvas[coord+1] == 255 && canvas[coord+2] == 0)return; 

    if(canvas[coord] == 255 && canvas[coord+1] == 255 && canvas[coord+2] == 255)return; 

    //colors 
    canvas[coord] = 255; 
    canvas[coord+1] = 255; 
    canvas[coord+2] = 255; 

    //recursive 
    seed_fill(x,y-1); 
    seed_fill(x,y+1); 
    seed_fill(x-1,y); 
    seed_fill(x+1,y); 
} 
} 

三葉草是你的400x400像素總數

大當我運行該項目,它告訴我此錯誤消息:在線程

異常「 AWT-EventQueue-0「java.lang.StackOverflowError 在行代碼14,30和31

顯然有一個遞歸問題,但我不是那麼聰明,想出如何將代碼更改爲F生病那大對象。

感謝您的任何建議和幫助。

+0

它看起來像每次調用'seed_fill'爲每個鄰居調用'seed_fill'。所以如果你在'(a,b)'上調用它,並且在'(c,d)'上調用它,那麼_that_會再次在'(a,b)'上調用它。你得到無限遞歸。你需要重新安排你的函數調用和檢查來避免這種情況。 – khelwood 2014-11-22 20:28:47

回答

1

seed_fill()要求seed_fill()其4個鄰國,要求seed_fill()其4個鄰國,要求seed_fill()其4個鄰國,要求seed_fill()其4個鄰居,等等

所以,你最終有無盡的reursive呼叫。例如,調用它爲(0,1)調用它爲(1,1),調用它爲(0,1),調用它爲(1,1)等。