我制作了一个生成图块/像素的程序。 在这个程序中是一个用来填补空白和漏洞的函数,这就是我打算如何工作:
方法被赋予整数限制。然后,此方法将进行油漆桶式递归,将其瓷砖重新绘制为新的瓷砖(整数类型3),并在遇到实心瓷砖时停止。
一旦方法填充了超出限制的多个tile,该方法就会退出并返回一个false语句,告诉该区域的区域大于给定的限制。否则,如果递归方法一起停止并且已填充封闭区域内的所有空格而不破坏此限制,则返回true。
这里的问题是我不知道如何制作节目"等等"用于在返回值之前停止工作的递归方法。我试图做一个"等待"在返回之前经过while循环的变量,但结果并不好。
以下是源代码:
// 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 :(得分:0)
您的代码存在一些问题,
tempBoolean
变量始终设置为false;
num
变量都会回退到原始值,因此递归将处理的像素数超过limit
。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;
}