2015-06-11 60 views
0

我做了一個程序,生成瓷磚/像素。 在這個程序中是一個函數,用於填補空白和洞,這裏是我打算如何工作:Java遞歸遞歸值(桶填充工具)

一個方法給出了一個整數限制。然後,這種方法通過油漆桶狀遞歸將其瓦片重新繪製到新的瓦片(整數類型3),並在遇到實體瓦片時停止。

只要該方法填充的瓦片數量超過限制,該方法就會退出並返回一個錯誤語句,告訴該區域的面積大於給定的限制。否則,如果遞歸方法全部停止,並且填充了封閉區域內的所有空格而沒有突破該限制,則返回true。

這裏的問題是我不知道如何讓程序「等待」遞歸方法在返回值之前停止工作。我試圖讓一個「等待」變量在返回前經過一段時間的循環,但結果並不好。

這裏是源代碼:

// Method called in other parts of the program. 
private boolean checkNum(int x, int y, int limit){ 

     int num = 0; 
     checkNum(x,y,num,limit,count); // I think the recursive methods following this one are carried out after the statement on the next line. That is the cause of the issue. 
       return tempBoolean; 
} 


//Recursive method called be previous one and itself. 
private void checkNum(int x, int y, int num, int limit,int count){ 
     tempBoolean = false; 


     if ((grid[x][y] == 3) || (grid[x][y] == 1)) { 
      return; 
     } 




     grid[x][y] = 3; 
     System.out.println(num); 
     num++; 

     if (num > limit) { 
      tempBoolean = false; // This system for setting an external variable and then returning it in a different method is probably not the right way to do it. 
      return; 
     } 


     checkNum(x + 1,y,num,limit,count); 
     checkNum(x - 1,y,num,limit,count); 
     checkNum(x,y + 1,num,limit,count); 
     checkNum(x,y - 1,num,limit,count); 

} 

回答

0

有幾個問題,你的代碼,

  1. 我不認爲你需要遞歸在所有的這一點。循環會做。
  2. tempBoolean變量總是被設置爲false;
  3. 每次遞歸調用後,您num變量回落到原來的值,因此遞歸將處理超過limit更多的像素。
  4. 如果您認爲您的return tempBoolean;語句在遞歸調用完成之前執行,否則不會發生。

要修復它使用遞歸本身,你這樣的事情,而不是,

// Method called in other parts of the program. 
private boolean checkNum(int x, int y, int limit){ 

     int num = 0; 
     num = checkNum(x,y,num,limit,count); // I think the recursive methods following this one are carried out after the statement on the next line. That is the cause of the issue. 

     return (num <= limit); 
} 


//Recursive method called be previous one and itself. 
private int checkNum(int x, int y, int num, int limit,int count){ 

     if (num > limit) { 
      return num; 
     } 

     if ((grid[x][y] == 3) || (grid[x][y] == 1)) { 
      return num; 
     } 




     grid[x][y] = 3; 
     System.out.println(num); 
     num++; 



     num = checkNum(x + 1,y,num,limit,count); 
     num = checkNum(x - 1,y,num,limit,count); 
     num = checkNum(x,y + 1,num,limit,count); 
     num = checkNum(x,y - 1,num,limit,count); 

     return num; 
}