Yochert
Yochert

Reputation: 85

4-way flood fill function without passing starting color

I need to write a recursive flood fill function which prototype looks like this:

bool fill(PixMap& image,Pixel fillColour,int x, int y)

image is the "image" part of which will be flood filled, fillColour is the color that gonna be used to fill the certain area of a picture. x and y ary coordinates of first pixel that will be filled. Problem is that algorithms that I found online include also oldColor variable, or the original color that starting pixel has. And if pixel that gonna be filled with the color is not the same color as the original one than recursion stops.

    void floodFill4(int x, int y, int newColor, int oldColor) 
{ 
    if(x >= 0 && x < w && y >= 0 && y < h && screenBuffer[x][y] == oldColor && screenBuffer[x][y] != newColor) 
    { 
        screenBuffer[x][y] = newColor; //set color before starting recursion

        floodFill4(x + 1, y,     newColor, oldColor);
        floodFill4(x - 1, y,     newColor, oldColor);
        floodFill4(x,     y + 1, newColor, oldColor);
        floodFill4(x,     y - 1, newColor, oldColor);
    }     
}

However, in my prototype there is no such variable and I does not allowed to change it. How do I do the recursion flood fill that does not flood all of the image?

Upvotes: 2

Views: 1160

Answers (1)

FRob
FRob

Reputation: 4041

Think about what the function prototype says:

Fill image at x/y with fillColor.

It does not say:

Fill image at x/y with fillColor when there is oldColor, else do nothing.

The latter its your floodfill4 prototype. When floodfill4 is called, it's not certain if a fill will occur, because it first has to check.

On the other hand, your target prototype will always fill -- that's why it doesn't need oldColor.

Long story short: instead of testing once for old color, do this instead:

if pixel at x/y is fillColor:
    return
save oldColor at x/y
replace pixel at x/y with fillColor

for all neighboring pixels:
    if pixel at neighbor is oldColor:
        recursive call

Upvotes: 1

Related Questions