gpt4 book ai didi

java - 当计数器从 1 开始时递归方法的堆栈溢出

转载 作者:行者123 更新时间:2023-11-30 09:06:45 25 4
gpt4 key购买 nike

<分区>

我编写了一个程序来读取包含 1 和 0 的矩阵的文本文件,该矩阵将递归循环以识别所有唯一的四连接区域(通过上、下、左、右移动连接的区域)。然后,我将每个区域中的 1 替换为标识符号,但是当我从 1 开始计算替换值时,出现堆栈溢出错误。我在构建我的递归方法时解决了这个问题,方法是从 2 开始,然后在一切完成后返回并将所有区域值递减 1,以便区域计数器在输出中从 1 开始。这有效,我的输出是正确的,但这感觉像是一个懒惰的解决方案。

我知道我需要一种方法来确定 1 是否已经被识别,这将允许我用 1s 替换一个区域并且仍然能够正确地读取网格,但我不确定是否有任何方法来查看是否元素是对象的成员。我试图构建一系列 if-else 语句来识别遇到的第一个 1 并从那里循环,但是当我再次到达该区域时,我要么得到堆栈溢出错误,要么得到奇怪的输出,例如第一个中的每个数字区域(应该用新的 1 代替)是一个不同的数字。编写第二个递归方法来处理遇到的第一个 1 是否更聪明,或者我从 2 开始然后递减所有值的事实真的让程序变得如此丑陋吗?

/**
* Scans the grid for 1s, calling the designateRegions method when unique
* 1s are found.
*/
public static void findRegions() {
int region = 2;//the counter variable in question
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nCols; j++) {
if (grid[i][j] == 1) {
//Ensure the value isn't part of a known region
if (j-1 >= 0 && grid[i][j-1] >= 1) {
grid[i][j] = grid[i][j-1];
} else if (i-1 >= 0 && grid[i-1][j] >= 1) {
grid[i][j] = grid[i-1][j];
} else {//if 1 is unique
Regions regionObject = new Regions(region);//instantiate a Regions object
regionCountList.add(regionObject);//add new Regions object to arraylist
designateRegions(grid, i, j, region, regionObject);//call recursive method designateRegions
region++;
}//end nested if-else block
}//end outer if statement
}//end inner for loop
}//end outer for loop

//this is stupid
for (int i = 0; i < nRows; i++) {
for (int j = 0; j < nCols; j++) {
if (grid[i][j] > 1) {
grid[i][j] = grid[i][j] - 1;//drop the value of each region by 1
}//end if statement
}//end inner for loop
}//end outer for loop

}//end findRegions method

/**
* Loops recursively to identify four-connected regions of 1s and change the
* value of the elements in the newly identified region.
* @param grid the 2d integer array containing the grid to be scanned
* @param r the row position
* @param c the column position
* @param region the identifier value for the region
* @param regionObject the object associated with each region
*/
private static void designateRegions(Integer[][] grid, int r, int c, int region, Regions regionObject) {
if (grid[r][c] == 0) { //base case
} else if (grid[r][c] == 1) {
grid[r][c] = region;//switch value of the 1 with appropriate region identifier
regionObject.regionCount++;
if (r - 1 >= 0) {
designateRegions(grid, r - 1, c, region, regionObject);//move up
}
if ((r + 1) < nRows) {
designateRegions(grid, r + 1, c, region, regionObject);//move down
}
if ((c + 1) < nCols) {
designateRegions(grid, r, c + 1, region, regionObject);//move right
}
if (c - 1 >= 0) {
designateRegions(grid, r, c - 1, region, regionObject);//move left
}
}
}//end findRegions method

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com