I had to use for the first time flood fill algorithm in order to solve a task from a homework. The main problem is that it seems that the call of the flood fill function I wrote doesn`t work.
My task is something very similar to the one described here: How can I find hole in a 2D matrix?
I used an algorithm from here: http://www.codeproject.com/Articles/6017/QuickFill-An-efficient-flood-fill-algorithm and I adapted it to what I need.
I have for example this matrix:
0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0 0 0
0 0 1 1 1 1 1 0 1 0
0 1 1 1 1 1 0 0 1 0
0 0 1 1 1 0 0 0 1 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 0 0 0
0 0 0 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
And I want to transform it in something like this:
0 0 0 0 0 0 0 0 0 0
0 0 0 2 2 0 0 0 0 0
0 0 2 2 2 2 2 0 3 0
0 2 2 2 2 2 0 0 3 0
0 0 2 2 2 0 0 0 3 0
0 0 0 0 2 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 4 4 4 4 4 4 0 0 0
0 0 0 4 4 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
and also to count the elements of every "area" or cluster.
In the main program, I search for the first element equal to 1 and send his position (x,y) to the function "color" (flood fill function) to become the "seed".
I tried to find the bugs using gdb - found nothing. I added some printf() to the code to see what is happening - everything works fine until I call the function "color" and then nothing happens. I searched the internet for a solution but I didn`t find something to solve this.
Here is the code of the flood-fill:
int color(int x,int y,int n,int**sim,int nr, int h, int w)
{
if (x < h && y < w)
if( sim[x][y] == 1 )
{
sim[x][y] = n;
printf ("%d %d ", x, y);//it does not print anything here
if (sim[x-1][y] != 1 && sim[x+1][y] != 1 && sim[x][y-1] != 1 && sim[x][y+1] != 1)
return nr; /*this happens when everything around is equal to 0 or n, so there is nothing to modify and the program should end*/
else
{
nr++;
color(x-1,y,n,sim,nr,h,w);
color(x+1,y,n,sim,nr,h,w);
color(x,y-1,n,sim,nr,h,w);
color(x,y+1,n,sim,nr,h,w);
}
}
}
And the call in the main function:
int **s;
s = malloc(m*sizeof(int *));
for(i=1; i <= h; i++)
s[i] = malloc(m*sizeof(int));
a=0;
b=0;
while (a <= h && b <= w)
{
k = 0;
for(i=a; i < h && k == 0; i++)
for(j=b; j < w; j++)
if( s[i][j] == 1 ) //find the first element = 1 and stop to its position
{k = 1; printf("%d %d ", i, j);}
printf("\n");
if(k == 1)
{
a = i;
b = j;
nr = color(i,j,c,s,0,h,w); //call the function
printf("%d,%d,%d,%d ", k, c, i, j);
cluster[c] = nr;
c++;
}
if (k == 0)
break; //if it is no area left to modify
}
I am a beginner and I have never used flood fill before. I am not even sure what is wrong: the flood fill code, the call of the function, or the way I pass the matrix sim[][] in the function. What is wrong?