简体   繁体   English

C语言中使用递归的“填充函数”

[英]a “fill function” using recursion in c language

I'm working on a simple drawing application, i need to create a "fill" function where the user will enter x,y values, the function should assume 4 connected neighbors, I tried to use recursion to do that but the program suddenly stops. 我正在一个简单的绘图应用程序上工作,我需要创建一个“填充”函数,用户将在其中输入x,y值,该函数应假定4个已连接的邻居,我尝试使用递归来做到这一点,但程序突然停止。 here is my function code : 这是我的功能代码:


void fill(int x, int y, struct pixels* screen)

{

int xx, yy, x1, y1;


    for (xx = -1; xx <= 1; xx++)
    {
        for (yy = -1; yy <= 1; yy++)
        {

            x1 = x + xx;
            y1 = y + yy;

            if ((x1 >= 0) && (x1 < screen->width))
            {
                if ((y1 >= 0) && (y1 < screen->height))
                {
                    if (screen->pixel[x1][y1] = '.')
                    {
                        screen->pixel[x1][y1] = '*';
                        fill(x1, y1, screen);
                    }
                }

            }
        }
    }
}

here's an image of how it should work when the user enters "fill 6 20" 这是用户输入“ fill 6 20”时应如何工作的图像

The problem with your recursive approach is that larger images tend to cause stack overflow, because the highest number of recursive invocations is controlled by the size of the larges "frontier" to be filled. 递归方法的问题在于,较大的图像往往会导致堆栈溢出,因为递归调用的最大数量由要填充的大块“边界”的大小控制。

One approach that could save you from stack overflow would be using a dynamically allocated queue of items. 一种可以使您免于堆栈溢出的方法是使用动态分配的项目队列。 Each queue element would store an {X, Y} pair of coordinates. 每个队列元素将存储一对{X, Y}坐标。 Initially you would put x , y passed into your function on the queue, and start the loop that goes on until the queue is empty. 最初,您会将传递给函数的xy放入队列中,并开始循环,直到队列为空。

Each time you extract the first element of the queue it becomes your current x , y . 每次提取队列的第一个元素时,它都会成为当前的xy Then you do your two nested loops the same way, except that rather than calling fill(x1, y1, screen); 然后,除了调用fill(x1, y1, screen);之外,您以相同的方式执行两个嵌套循环fill(x1, y1, screen); you add {x1, y1} to the end of the queue. 您将{x1, y1}添加到队列的末尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM