【发布时间】:2020-03-07 11:08:48
【问题描述】:
我正在解决一个问题,其中给出了一个预先填充有'o' 和空格字符的二维数组。我有一个循环遍历二维数组,一旦遇到'o',它应该调用一个递归方法,该方法将递归查找周围的单元格(上、下、左或右,而不是对角线) 'o',它将为所有连接单元格提供相同的标签。
我现在的代码有问题,因为它只会检查周围的 1 个单元格,因为我不确定如何设置递归调用。
public class NameGroups {
public static void main(String[] args) {
char population[][] = {
{'o','o','o',' ',' ',' ',' ',' ',' ',' '},
{'o','o','o',' ',' ',' ',' ',' ','o','o'},
{'o','o',' ',' ',' ',' ',' ',' ',' ',' '},
{' ','o',' ',' ',' ',' ',' ',' ',' ',' '},
{' ','o',' ',' ',' ','o',' ',' ',' ',' '},
{' ',' ',' ',' ',' ','o','o',' ',' ',' '},
{' ',' ',' ',' ',' ','o',' ',' ',' ',' '},
{' ',' ',' ',' ',' ',' ',' ',' ',' ',' '},
{'o','o',' ',' ',' ',' ',' ',' ',' ',' '},
{'o','o',' ',' ',' ',' ',' ',' ',' ',' '}
};
int groups = numberOfGroups(population);
for (char[] line : population) {
for (char item : line) {
System.out.print(item);
}
System.out.println();
}
System.out.print("There are " + groups + " groups.");
}
public static int numberOfGroups(char[][] population) {
int numGroups = 0;
char name = '1';
for(int row = 0; row < population.length; row++) {
for(int col = 0; col < population[row].length; col++) {
if(population[row][col] == 'o') {
nameGroups(population, name++, row, col);
numGroups++;
}
}
}
return numGroups;
}
private static boolean nameGroups(char[][] population, char name, int row, int col) {
if (population[row][col] == 'o') {
population[row][col] = name;
}
if(checkBounds(population, row + 1, col)) {
if (population[row + 1][col] == '*') {
return nameGroups(population, name, row + 1, col);
}
}
if(checkBounds(population, row - 1, col)) {
if (population[row - 1][col] == '*') {
return nameGroups(population, name, row - 1, col);
}
}
if(checkBounds(population, row, col + 1)) {
if (population[row][col + 1] == '*') {
return nameGroups(population, name, row, col + 1);
}
}
if(checkBounds(population, row, col - 1)) {
if (population[row][col - 1] == '*') {
return nameGroups(population, name, row, col - 1);
}
}
return true;
}
private static boolean checkBounds(char[][] population, int row, int col) {
if(row < 0) {
return false;
} else if(col < 0) {
return false;
} else if(row >= population.length) {
return false;
} else if(col >= population[row].length) {
return false;
}
return true;
}
}
预期的输出将是:
1,1,1, , , , , , ,
1,1,1, , , , , ,2,2
1,1, , , , , , , ,
,1, , , , , , , ,
,1, , , ,3, , , ,
, , , , ,3,3, , ,
, , , , ,3, , , ,
, , , , , , , , ,
4,4, , , , , , , ,
4,4, , , , , , , ,
我的代码的问题是它将通过 if 语句并找到一个邻居并返回该单元格。它不会返回并返回其他周围的单元格。我不确定如何处理这个递归问题。我也不确定递归方法应该使用什么数据类型。
【问题讨论】:
-
你好,我看不出递归在哪里,应该有方法调用自己吧?
-
@Eric nameGroups()
-
@Tyler 我的错,我没有滚动查看是否有额外的代码????
标签: java recursion multidimensional-array