Floodfill implementetion

假如想象 提交于 2019-12-12 02:52:02

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!