我已经使用递归编写了以下程序,但我不知道如何以非递归方式编写它。每次我运行我的非递归版本时,数字都会偏离。关于如何在没有递归的情况下编写以下方法的任何建议?
int countCells(color grid[ROWS][COLS], int r, int c) {
if (r < 0 || r >= ROWS || c < 0 || c >= COLS) {
return 0;
} else if (grid[r][c] != ABNORMAL) {
return 0;
} else {
grid[r][c] = TEMPORARY;
return 1
+ countCells(grid,r-1,c-1) + countCells(grid,r-1,c)
+ countCells(grid,r-1,c+1) + countCells(grid,r,c+1)
+ countCells(grid,r+1,c+1) + countCells(grid,r+1,c)
+ countCells(grid,r+1,c-1) + countCells(grid,r,c-1);
}
}
这是我尝试过的顺便说一句:
int countCells(color grid[ROWS][COLS], int r, int c)
{
int temp = 0;
if (r < 0 || r >= ROWS || c < 0 || c >= COLS)
{
return 0;
}
else if (grid[r][c] != ABNORMAL)
{
return 0;
}
else
{
int original_row = r;
int original_column = c;
while(r >= 0 && row < ROWS && c >= 0 && c < COLS && grid[r][c] == ABNORMAL)
{
grid[r][c] = TEMPORARY;
temp = temp + 1;
r = r - 1;
c = c - 1;
}
r = original_r;
c = original_c;
while(r >= 0 && r < ROWS && c >= 0 && c < COLS && grid[r][c] == ABNORMAL)
{
grid[r][c] = TEMPORARY;
temp = temp + 1;
r = r - 1;
}
r = original_r;
c = original_c;
while(r >= 0 && r < ROWS && c >= 0 && c < COLS && grid[r][c] == ABNORMAL)
{
grid[r][c] = TEMPORARY;
temp = temp + 1;
r = r - 1;
c = c + 1;
}
r = original_r;
c = original_c;
while(r >= 0 && r < ROWS && c >= 0 && c < COLS && grid[r][c] == ABNORMAL)
{
grid[r][c] = TEMPORARY;
temp = temp + 1;
c = c + 1;
}
r = original_r;
c = original_c;
while(r >= 0 && r < ROWS && c >= 0 && c < COLS && grid[r][c] == ABNORMAL)
{
grid[r][c] = TEMPORARY;
temp = temp + 1;
r = r + 1;
c = c + 1;
}
r = original_r;
c = original_c;
while(r >= 0 && r < ROWS && c >= 0 && c < COLS && grid[r][c] == ABNORMAL)
{
grid[r][c] = TEMPORARY;
temp = temp + 1;
r = r + 1;
}
r = original_r;
c = original_c;
while(r >= 0 && r < ROWS && c >= 0 && c < COLS && grid[r][c] == ABNORMAL)
{
grid[r][c] = TEMPORARY;
temp = temp + 1;
r = r + 1;
c = c - 1;
}
r = original_r;
c = original_c;
while(r >= 0 && r < ROWS && c >= 0 && c < COLS && grid[r][c] == ABNORMAL)
{
grid[r][c] = TEMPORARY;
temp = temp + 1;
c = c - 1;
}
r = original_r;
c = original_c;
return temp;
}
}