I want to find area of contiguous 1 in two dimension array like this

00000000000000000

00000011111100000

00000011011000000

00000000001110000

00000000000000000

Contiguous area of number 1 = 13

I write FindAreaof1 function below and m_tempData(x,y) is two dimension area

I call FindAreaof1 function by this loop

for (y=0; y< width; y++){

for (x=0; x< width; x++){

if (m_tempData(x,y) == 1){

InterestArea = FindAreaof1(x,y);

If (InterestArea > 5000)

{

Interestx = x;

Interesty = y;

}

}

}

////This is FindAreaof1 function//////

long FindAreaof1(long x, long y)

{

long count ;

if (m_tempData(x,y)==0) return 0;

m_tempData(x,y) = 0;

count = 1 + FindAreaof1(x, y-1) + FindAreaof1 (x+1, y-1)

+ FindAreaof1 (x+1, y) + FindAreaof1 (x+1, y+1)

+ FindAreaof1 (x, y+1) + FindAreaof1 (x-1, y+1)

+ FindAreaof1 (x-1, y) + FindAreaof1 (x-1, y-1);

return count;

}

In the above example I can find FindAreaof1 = 13

If FindAreaof1 has small value ,it can find FindAreaof1.

But if FindAreaof1 has large value , it show message box and tell me there is Stack Overflow error.

I think this error cause by time of resursion is large. I want to know how to exit loop FindAreaof1 when count more than 5000 and send 5000 to FindAreaof1(x,y)

Because I think if exit loop when count >= 5000 can solve Stack Overfolw error and I want only position x and y which has Findareaof1 more than 5000.