c - 洪水填充算法

标签 c algorithm primitive flood-fill graphic

我在一个简单的 C 图形库中使用 turbo 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 
}

这是我为洪水填充功能编写的代码:

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;
    }
}

但它仍然不起作用,当我尝试填充大面积区域时它就停止了,因为我在我的程序中使用 640 X 480 分辨率,这确实是个问题;有什么想法为什么它不起作用吗?

最佳答案

与其将每个像素压入堆栈,不如尝试在水平方向填充尽可能多的像素,然后再压入堆栈的新位置。查看Wikipedia article进行讨论。

关于c - 洪水填充算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1879371/

相关文章:

c++ - printf 与 long long int 的结果不一致?

algorithm - 概念上简单的线性时间后缀树结构

Java: float, long 局部初始化

c++ - 为什么在 c/c++ 中,开关的优化方式与链式 if else 不同?

c - 取消引用指向不完整类型链表的指针 - C

python - 有效地连接地址行

Java多维数组被认为是原始或对象

c++ - 自定义字节大小?

c++ - 如何捕获 x86 上的数据对齐错误(Sparc 上的 SIGBUS)

database - 我可以做些什么来处理网站上用户的不良行为?