【发布时间】: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:我目前就读于同一个班级,这是一个作业。