这是我基于维基百科定义实现的基于堆栈的泛洪算法的C#代码。在编码时,我只想看到它起作用。它确实做到了。然后,我想知道实际上有多少像素被填充了。因此,在我的代码中,我将返回类型更改为整数,并返回“ctr”变量。但是“ctr”变量实际上是填充像素数量的两倍左右(我编写了一个单独的函数,其唯一目的是计算这些像素 - 只是为了确定)。
可以有人告诉我为什么变量“ctr”会增加两倍?
*Pixel类仅用作位图像素的x,y和颜色值的容器。
可以有人告诉我为什么变量“ctr”会增加两倍?
*Pixel类仅用作位图像素的x,y和颜色值的容器。
public Bitmap floodfill(Bitmap image, int x, int y, Color newColor)
{
Bitmap result = new Bitmap(image.Width, image.Height);
Stack<Pixel> pixels = new Stack<Pixel>();
Color oldColor = image.GetPixel(x, y);
int ctr = 0;
pixels.Push(new Pixel(x, y, oldColor));
while (pixels.Count > 0)
{
Pixel popped = pixels.Pop();
if (popped.color == oldColor)
{
ctr++;
result.SetPixel(popped.x, popped.y, newColor);
pixels.Push(new Pixel(popped.x - 1, popped.y, image.GetPixel(x - 1, y));
pixels.Push(new Pixel(popped.x + 1, popped.y, image.GetPixel(x + 1, y));
pixels.Push(new Pixel(popped.x, popped.y - 1, image.GetPixel(x, y - 1));
pixels.Push(new Pixel(popped.x, popped.y + 1, image.GetPixel(x, y + 1));
}
}
return result;
}
ctr
意思是counter
,那么把它叫做counter
是没有问题的。 - Austin Salonen