问题
I have a problem with my flood fill function:
void floodfill(int x, int y,Pixel old, Pixel new){
Pixel current = getPixel(x,y);
if(current.r == old.r && current.g == old.g && current.b == old.b){
setPixel(x,y,new);
floodfill(x+1,y,old,new);
floodfill(x-1,y,old,new);
floodfill(x,y+1,old,new);
floodfill(x,y-1,old,new);
floodfill(x+1,y+1,old,new);
floodfill(x-1,y-1,old,new);
floodfill(x+1,y+1,old,new);
floodfill(x-1,y+1,old,new);
}
}
In struct 'Pixel' I have rgb values of the pixel. I am trying to fill a square and when I come to the border of the square (color changes from white to black, the border is at point x=200) the function is not changing to other pixels but just endlessly changing the x value to 198 and 199 (nevermind the y value). Can someone tell me what I am doing wrong?
回答1:
This sounds like setPixel isn't setting the colour of (x,y) to the "new". So, what's happening is the following sequence of recursive calls:
(199,y)->(200,y) [This stops because the border doesn't have the same colour as old] ->(198, y)->(199,y) [(199, y) is getting called because setPixel likely didn't change the colour of (199, y)]->...
回答2:
One possible issue is that you are filling (x+1,y+1)
twice and missing (x+1,y-1)
:
floodfill(x+1,y,old,new);
floodfill(x-1,y,old,new);
floodfill(x,y+1,old,new);
floodfill(x,y-1,old,new);
floodfill(x+1,y+1,old,new);
floodfill(x+1,y-1,old,new); //Missing this case
floodfill(x-1,y+1,old,new);
floodfill(x-1,y-1,old,new);
来源:https://stackoverflow.com/questions/24315491/floodfill-implementetion