我需要编写一个递归洪泛填充函数,其原型如下:
bool fill(PixMap& image,Pixel fillColour,int x, int y)
图像是"图像"的一部分,它将被洪水填充,fillColour是将用于填充图片的特定区域的颜色。将被填充的第一个像素的x和y坐标。问题是,我在网上找到的算法还包括oldColor变量,或者起始像素的原始颜色。如果要填充颜色的像素与原始像素的颜色不同,则递归停止。
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);
}
}
然而,在我的原型中没有这样的变量,我不允许更改它。我如何进行递归泛洪填充,而不泛洪所有图像?
想想函数原型是怎么说的:
用fillColor
填充x/y处的图像。
它没有说:
当存在oldColor
时,用fillColor
填充x/y处的图像,否则不执行任何操作。
后者是您的floodfill4
原型。当调用floodfill4
时,不确定是否会发生填充,因为它首先必须进行检查。
另一方面,您的目标原型将始终填充——这就是为什么它不需要oldColor
。
长话短说:与其测试一次旧颜色,不如这样做:
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