gpt4 book ai didi

c - 洪水填充算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:13:25 25 4
gpt4 key购买 nike

我在一个简单的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com