Я написал следующую программу, используя рекурсию, но я не могу понять, как написать ее не рекурсивно. Каждый раз, когда я запускаю свою нерекурсивную версию, цифры меняются. Любые предложения о том, как написать следующий метод без рекурсии?
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;
}
}