I have written the following program, using recursion, but I can't figure out how to write it non-recursively. Every time I run my non-recursive version the numbers are way off. Any suggestions on how to write the following method without recursion?
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);
}
}
This is what I have tried btw:
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;
}
}