# Ask about stack overflow when recursive

• 05-17-2002
I want to find area of contiguous 5 in two dimension array like this

00000000000000000
00000055555500000
00000055055000000
00000000005550000
00000000000000000

Contiguous area of number 1 = 13
I write FindAreaof5 function below and m_tempData(x,y) is data in this array (0 or 5)
I call FindAreaof5 function by this loop

for (y=0; y< height; y++){
for (x=0; x< width; x++){
if (m_tempData(x,y) == 5){
InterestArea = FindAreaof5(x,y);
}
}

////This is FindAreaof5 function//////
long FindAreaof5(int x, int y)
{
m_tempData(x,y) = 0;
count++;
FindAreaof5(x, y-1);
FindAreaof5 (x+1, y-1);
FindAreaof5 (x+1, y);
FindAreaof5 (x+1, y+1);
FindAreaof5 (x, y+1);
FindAreaof5 (x-1, y+1);
FindAreaof5 (x-1, y);
FindAreaof5 (x-1, y-1);
return count;
}

In the above example I can find FindAreaof5 = 13
If FindAreaof5 has small value ,it can find FindAreaof5.
But if FindAreaof5 has large value (more than 12000) , it show message box and tell me there is Stack Overflow error.
I think this error cause by time of resursive is so long. I want to know how to solve this problem. Someone suggest me to extend stacksize or change to non recursive but I do not know how to do that. If you know how to solve my problem, please tell me. Thank you very much.
• 05-17-2002
Salem
You need to stop your algorithm from backtracking over where you've been already

FindAreaof5(x, y-1);
...
FindAreaof5 (x, y+1);

Type thing gets you back to where you started, and so the process repeats until you're out of stack
• 05-17-2002
change code
I type FindAreaof5 wrong I want to change to this
long FindAreaof5(int x, int y)
{
if (m_tempData(x,y)==0) return count;
m_tempData(x,y) = 0;
count++;
FindAreaof5(x, y-1);
FindAreaof5 (x+1, y-1);
FindAreaof5 (x+1, y);
FindAreaof5 (x+1, y+1);
FindAreaof5 (x, y+1);
FindAreaof5 (x-1, y+1);
FindAreaof5 (x-1, y);
FindAreaof5 (x-1, y-1);
}