我编写了一个程序来读取包含 1 和 0 矩阵的文本文件,该文件将递归循环以识别所有唯一的四连接区域(通过上、下、左、右移动连接的区域)。然后,我用标识符号替换每个区域中的 1,但是当我在 1 开始计数替换值时,出现堆栈溢出错误。我在构建递归方法时解决了这个问题,方法是从 2 开始,然后在一切完成后返回,并将所有区域值递减 1,以便区域计数器在输出中从 1 开始。这有效,我的输出是正确的,但这感觉像是一个懒惰的解决方案。
我知道我需要一种方法来识别 1 是否已被识别,这将允许我用 1 替换一个区域,并且仍然能够正确读取网格,但我不确定是否有任何方法来查看元素是对象的成员。我尝试构建一系列 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
最佳答案
您正确地识别了问题:递归代码需要标记每个已访问过的网格元素,以防止程序追逐自己的尾部。
用不同的值 (2) 标记访问过的单元格是一种有效的策略。另一种可能性是传递一个由 boolean[nRows][nCols]
组成的单独网格,其中的单元格中包含 true
来标识访问的单元格。
我认为您的解决方案更干净,因为它不需要分配任何额外的内存。
关于java - 当计数器从 1 开始时,递归方法出现堆栈溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24295180/