【发布时间】:2013-01-16 00:56:43
【问题描述】:
这是我基于堆栈的洪水填充算法的 C# 实现(我基于维基百科的定义)。早些时候在编码时,我只想看到它工作。它确实做到了。然后,我想知道实际填充的像素数。所以在我的代码中,我将返回类型更改为 int 并返回 "ctr" 变量。但后来发现 ctr 大约是实际填充像素数的两倍(我创建了一个单独的函数,其唯一目的是计算这些像素 - 只是为了确定)。
谁能解释一下变量 "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没有任何问题。
标签: c# flood-fill