【发布时间】:2018-10-30 01:40:26
【问题描述】:
我对导致堆栈溢出错误的原因进行了一些研究,我可以得出结论,这是由程序中的递归函数引起的,该函数应该“计算数组中的岛数”。我了解导致问题的原因,但不确定为什么会发生这种情况,或者我的主要问题是实际该怎么做。我发现如果我通过让程序反复向控制台打印一些内容来减慢程序的速度,它可以工作,但需要很长时间才能完成。有没有办法可以保持程序速度而不会出错,或者有更好的方法来解决问题(搜索“岛屿数量”以找到问题)。此外,该数组是二维的,大小为 1050 x 800。
public class NumOfIslands {
static boolean[][] dotMap = new boolean[1050][800];
static boolean visited[][] = new boolean[1050][800];
static int total = 0;
public static void main(String args[]) {
defineArrays();
run();
}
public static void findObjects(int xCord, int yCord) {
for(int y = yCord - 1; y <= yCord + 1; y++) {
for(int x = xCord - 1; x <= xCord + 1; x++) {
if(x > -1 && y > -1 && x < dotMap[0].length && y < dotMap.length) {
if((x != xCord || y != yCord) && dotMap[x][y] == true && visited[x][y] != true) {
visited[x][y] = true;
findObjects(x,y);
//System.out.println("test");
}
}
}
}
}
public static void defineArrays() {
for(int y = 0; y < 800; y++) {
for(int x = 0; x < 1050; x++) {
dotMap[x][y] = true;
}
}
}
public static int run() {
//dotMap = DisplayImage.isYellow;
System.out.println(dotMap.length + " " + dotMap[0].length);
int objects = 0;
for(int y = 439; y < 560/*dotMap[0].length*/; y++) {
for(int x = 70; x < 300/*dotMap.length*/; x++) {
if(dotMap[x][y] == true && visited[x][y] != true) {
visited[x][y] = true;
objects++;
findObjects(x,y);
}
}
}
System.out.println("total" + total);
System.out.println(objects);
return objects;
}
}
【问题讨论】:
-
你为什么要做
recursive和looping。 -
@ScaryWombat 你是什么意思?
-
通常使用
recursive而不是循环 -
@ScaryWombat for 循环用于检查错误中的每个值。如果使用递归函数达到任何值,则单独的数组存储它被访问过的值。我需要循环的原因是因为我正在计算数组中连接的对象的数量,而且我知道它会不止一个,所以我认为我需要循环和函数。可能有更好的方法来做到这一点,我错过了。
-
但是由于您似乎正在根据嵌套的 for 循环访问每个元素,您是否需要递归调用该方法?
标签: java recursion count self gaps-and-islands