洪水填充算法

ezg*_*gar 1 c algorithm primitive flood-fill graphic

即时通讯使用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 
}
Run Code Online (Sandbox Code Playgroud)

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

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 < 640 && read_pixel(x+1, y) == color_to_replace)
            if(push(&stack, x+1, y) == 0)
                return;
        if(x-1 >= 0 && read_pixel(x-1, y) == color_to_replace)
            if(push(&stack, x-1, y) == 0)
                return;
        if(y+1 < 480 && read_pixel(x, y+1) == color_to_replace)
            if(push(&stack, x, y+1) == 0)
                return;
        if(y-1 >= 0 && read_pixel(x, y-1) == color_to_replace)
            if(push(&stack, x, y-1) == 0)
                return;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Aar*_*lla 5

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