First find a non-visited cell, and start recursion.
disclaimer: This is not java, it's pseudo C without most declarations and headers. C is anyway much easier to convert to java... Use a global or a class member for the count if necessary.
To make things easier, surround your N*N array by guards.
// with -1 -1 -1 -1
// -1 x x -1
// -1 -1 -1 -1
for (i=N+2;i<(N+2)*(N+1);i++) { // exact starting and ending locations are disclosed
if (k=array[i]!=-1) {
j=1;
flood_fill(array,i,k,&j);
if (j>max) { max=j; max_number=k; }
}
}
#define UP -(N+2)
#define DOWN (N+2)
#define LEFT -1
#define RIGHT 1
int flood_fill(int *array, int position, int value_to_compare, int *count)
{
// for each direction UP,DOWN,RIGHT,LEFT
static const int directions[4]={UP,DOWN,RIGHT,LEFT];
int t;
for (t=0;t<4;t++)
if (array[position + directions[t]]==value_to_compare) {
array[position + directions[t]] = -1;
*count+=1;
flood_fill(array, position+directions[t], value_to_compare, count);
}
}