【问题标题】:Flood fill algorithm in c++C ++中的洪水填充算法
【发布时间】:2011-07-10 17:33:06
【问题描述】:

我正在尝试编写代码来对图像进行颜色填充,并且我正在使用 Stacks。 (堆栈和队列仍然是新手,所以我不确定哪个会更好)。无论如何,我想我已经掌握了基本概念,但是我的代码存在缺陷:

animation DFSfill(BMP& img, int x, int y, colorPicker & fillColor, int tolerance, int frameFreq) {


Stack<RGBApixel> s;
s.push(*img(x,y));
int actualTol;
int height, width;
width=img.TellWidth();
height=img.TellHeight();
int counter=1;
animation finalAnimation;
RGBApixel top;

bool visited[width][height];
for(int i=0;i<width;i++)
    for(int j=0;j<height;j++)
        visited[x][y]=false;



while(!s.isEmpty()){
    top = s.peek();
    s.pop();

    actualTol=(top.Red-fillColor(x,y).Red)^2
+(top.Blue-fillColor(x,y).Blue)^2+(top.Green-fillColor(x,y).Green)^2;

    //check 
    if(x<0 || x>=width)
        continue;
    if(y<0 || y>=height)
        continue;
    if (visited[x][y]==true)
        continue;
    if(actualTol>tolerance)
        continue;

    visited[x][y]=true;
    img(x,y)->Red=fillColor(x,y).Red;
    img(x,y)->Blue=fillColor(x,y).Blue;
    img(x,y)->Green=fillColor(x,y).Green;
    counter++;

    //visit adjacent nodes


    s.push(*img(x+1, y));//right

    s.push(*img(x, y-1));//down

    s.push(*img(x-1, y));//left

    s.push(*img(x, y+1));//up

    if((counter%frameFreq)==0)
        finalAnimation.addFrame(img);
}

return finalAnimation;  

}

所以我认为问题,或者至少在我看来,是当访问相邻节点时,我在每个循环中访问相同的节点,对吗?有什么解决方法?

【问题讨论】:

  • 顶级提示:bool visited[width][height] = {0}; 让编译器为您进行初始化。
  • 为什么要从问题中删除代码?
  • @RageD:你为什么要添加作业标签?他说这是家庭作业吗? @iRobot:是吗?
  • @Benjamin:我目前就读于同一个班级,这是一个作业。

标签: c++ algorithm stack


【解决方案1】:

您应该在堆栈中保存坐标,而不是颜色。无需保存*img(x+1,y),您只需保存x+1,y。您可以使用包含两个坐标的struct 来执行此操作。

保存坐标可以让您穿越您正在填充的区域。保存颜色并没有任何意义。

您可以通过使用调试器一步一步地进入代码并查看您正在将什么推入堆栈以及从堆栈中取出什么来自行发现这个错误。

在尝试实施算法之前对算法有充分的了解也有帮助。要获得这种理解,您可以使用笔和纸在一个小玩具示例上手动运行算法。

【讨论】:

  • 此外,如果您的测试结果呈阳性,您应该继续旅行(对于当前职位)。
  • @stefan,不要破坏他的所有乐趣
  • 所以你是说我的堆栈应该是一个整数堆栈?
  • 这样看:目前你并没有改变 x 和 y 的初始值。 ;)
  • @iRobot:为什么不能创建新课程?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 2015-11-19
相关资源
最近更新 更多