【发布时间】:2019-10-15 23:58:48
【问题描述】:
我只是想知道我对递归的使用是否正确。该代码适用于预期目的;但是,我不确定它是否真的在进行递归。我尝试过跟踪我的程序,但我不明白为什么我的输出是正确的。基本上,该程序接收一个包含“*”的空格和 blob 的数据文件,并且我的程序应该递归地计算给定空间和 blob 数组中特定行和列的 blob 数。问题是我不确定为什么当我使用诸如北、南、东、西之类的变量时,它能够成功地将值返回给我,因为似乎在递归期间,每个变量都只存在于该调用中。另外,我不确定为什么 north = count(row,col+1) 会给出一个北的值,因为每次我遍历 count 的递归时,它似乎并没有停止在北的确定值上,因为就像它似乎并没有停下来说返回 1 作为北。
public static int count(int row, int col) {
int north = 0, south = 0, east = 0, west = 0;
if (map[row][col] == BLOB) {
map[row][col] = MARKED;
if (map[row][col+1] == BLOB) {
north = count(row,col+1);
}
//Go South
if (map[row][col-1] == BLOB) {
south = count(row, col-1);
}
//Go East
if (map[row+1][col] == BLOB) {
east = count(row+1, col);
}
//Go West
if (map[row-1][col] == BLOB) {
west = count(row-1, col);
}
return (1 + north + south + east + west);
}
return 0;
【问题讨论】: