recursive flood fill using 2D array

A common operation on images is called "flood fill", which takes three inputs:

1. a row number, x
2. a column number , y
3. a (new) colour d

The flood fill operation starts by changing the colour of the pixel at location ( x , y ) from its original colour c to the new colour d. Then, all neighbouring pixels (i.e. those pixels to the left, right, above and below, of the pixel at ( x , y )) whose colour is also c will have their colour changed to the new colour d and the process continues on the neighbours of the changed pixels until there are no more pixel locations to consider.

I have to write code to perform the flood fill operation using a recursive function and I am fairly lost. This is what I initially tried:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//function performs flood fill operation on image
void floodFill( unsigned int fpaRow, unsigned int fpaCol, int fpaColour, int fpaImage[][MAX_COL] )
{
	//if the pixels are not the same colour
	if ( fpaImage[fpaRow][fpaCol] != fpaImage[fpaRow][fpaCol] )
	{
		//display image
		display( fpaImage );
		return;
	}
	else
	{
		//change the colour
		fpaImage[fpaRow][fpaCol] = fpaColour;

		//check pixel above
		floodFill( fpaRow+1, fpaCol, fpaColour, fpaImage );

		//check pixel below
		floodFill( fpaRow-1, fpaCol, fpaColour, fpaImage );

		//check pixel to right
		floodFill( fpaRow, fpaCol+1, fpaColour, fpaImage );

		//check pixel to left
		floodFill( fpaRow, fpaCol-1, fpaColour, fpaImage );

		return;
	}
}
if ( fpaImage[fpaRow][fpaCol] != fpaImage[fpaRow][fpaCol] ) Is A equal to A?

You need to make the recursive call only if your neighbour has the same colour that you used to have.

Also, you need to care about out of bounds. That can be done with a sentinel (a value in the borders that does not appear nowhere else)
Last edited on
Topic archived. No new replies allowed.