洪水填充算法

我正在使用turbo C ++在C中使用一个简单的图形库,因为我正在开发一个非常原始版本的绘画风格程序,每个都运行良好,但我无法使洪水填充算法工作。 我使用4路泛洪填充算法,首先我尝试使用递归版本,但它只适用于小区域,填充大区域使其崩溃; 阅读我发现实现它的显式堆栈版本解决了问题,但我没有真正看到它。

我开发了这样的堆栈:

struct node { int x, y; struct node *next; }; int push(struct node **top, int x, int y) { struct node *newNode; newNode = (struct node *)malloc(sizeof(struct node)); if(newNode == NULL) //If there is no more memory return 0; newNode->x = x; newNode->y = y; newNode->next = *top; *top = newNode; return 1; //If we push the element correctly } int pop(struct node **top, int &x, int &y) { if(*top == NULL) //If the stack is empty return 0; struct node *temporal; temporal = *top; x = (*top)->x; y = (*top)->y; *top = (*top)->next; free(temporal); return 1; //If we pop an element } 

这是我对洪水填充function的代码:

 void floodFill(int x, int y, int color_to_replace, int color_to_fill) { if(color_to_replace == color_to_fill) return; struct node *stack = NULL; if(push(&stack, x, y) == 0) //If we can´t push the pixel return; while(pop(&stack, x, y) == 1) //While are pixels in the stack { pixel(x, y, color_to_fill); if(x+1 = 0 && read_pixel(x-1, y) == color_to_replace) if(push(&stack, x-1, y) == 0) return; if(y+1 = 0 && read_pixel(x, y-1) == color_to_replace) if(push(&stack, x, y-1) == 0) return; } } 

但它仍然无法工作,当我试图填补大区域它只是停止,因为我在我的程序中使用分辨率640 X 480这真的是一个问题; 任何想法为什么它不工作?

在推动堆栈上的新位置之前,尝试水平填充尽可能多的像素,而不是推动堆栈上的每个像素。 有关讨论,请参阅Wikipedia文章 。

我没有看到任何任何边界检查……

你确定X和Y值不会超出图片吗?

编辑:

额外的想法为什么它不能工作:

  • 读写像素函数有一个bug
  • 您获得的颜色值可以扩展到32位(因为例如您的图片是16位),您尝试写入和再次读回的颜色将完全不匹配。 (例如你写的颜色:0xff00ff但是你回来了:0xf800f8,因为颜色从16位扩大)这将导致洪水填充永远进行。