2015-06-11 59 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; 
}