用栈对递归算法进行优化,分为四个步骤:
1. 初始化。栈堆置空,将种子点(x,y)入栈。
2. 出栈,若栈空则结束,否则取栈顶元素(x,y),以y作为当前的扫描线。
3. 填充并确定种子所在区域。从当前点出发,左右两个方向进行填充,直到边界。
4. 确定新的种子,在左右边界中检查与当前扫描线上下相邻的两条扫描线。若存在未填充的像素,将最右像素作为种子压入栈。
主要的代码见下:~
void fill4(int x, int y)
{
int xl, xr, i;
bool tt;
while (!pp.empty()) pp.pop();
point pt;
pt.x = x;
pt.y = y;
pp.push(pt);
while (!pp.empty())
{
pt = pp.top();
pp.pop();
y = pt.y;
x = pt.x;
float color[3];
glReadPixels(x+1, y, 1, 1, GL_RGB, GL_FLOAT, color);
while (!is_equal(color, newcolor) && !is_equal(color, boundarycolor))
{
draw_a_point(x+1, y);
x++;
glReadPixels(x + 1, y, 1, 1, GL_RGB, GL_FLOAT, color);
glFlush();
}
xr = x - 1;
x = pt.x - 1;
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, color);
while (!is_equal(color, newcolor) && !is_equal(color, boundarycolor))
{
draw_a_point(x, y);
x--;
glReadPixels(x-1, y, 1, 1, GL_RGB, GL_FLOAT, color);
glFlush();
}
xl = x + 1;
x = xl;
y = y + 1;
while (x <= xr)
{
tt = false;
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, color);
while (!is_equal(color, newcolor) && !is_equal(color, boundarycolor))
{
tt = true;
x++;
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, color);
}
if (tt)
{
pt.x = x -1;
pt.y = y;
pp.push(pt);
tt = false;
}
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, color);
while ((is_equal(color, newcolor) || is_equal(color, boundarycolor)) && x <= xr)
{
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, color);
x++;
}
}
x = xl;
y = y - 2;
while (x <= xr)
{
tt = false;
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, color);
while (!is_equal(color, newcolor) && !is_equal(color, boundarycolor))
{
tt = true;
x++;
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, color);
}
if (tt)
{
pt.x = x - 1;
pt.y = y;
pp.push(pt);
tt = false;
}
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, color);
while ((is_equal(color, newcolor) || is_equal(color, boundarycolor)) && x <= xr)
{
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, color);
x++;
}
}
}
}
网友评论