递归崩溃

Recursion Crash

本文关键字:崩溃 递归      更新时间:2023-10-16

我正在编写一个程序来填充10(高度)*20(宽度)数组的颜色。当递归遇到包含字符#或*的框时,该框不会被着色。问题是,当我试图通过将当前框设置为中心并测试其8个周围框来执行递归时,程序崩溃并停止工作。我不知道我在哪里出错了。

void fillcolor(char fake[HEIGHT][WIDTH], char color, int startx, int starty)
{
        if (fake[starty][startx] != '#' && fake[starty][startx] != '*')
        {
            fake[starty][startx] = color;
            if (startx+1 <= 19 && starty+1 <= 9 && startx-1 >= 0 && starty-1 >= 0)
            {
                fillcolor(fake, color, startx, starty+1);
                fillcolor(fake, color, startx-1, starty);
                fillcolor(fake, color, startx-1, starty+1);
                fillcolor(fake, color, startx+1, starty+1);
                fillcolor(fake, color, startx, starty-1);
                fillcolor(fake, color, startx+1, starty);
                fillcolor(fake, color, startx-1, starty-1);
                fillcolor(fake, color, startx+1, starty-1);
            }
        }
}

下面是你想要的程序:

void fillcolor_recursive(char (&fake)[HEIGHT][WIDTH], char color, int x, int y, bool(&has_visited)[HEIGHT][WIDTH])
{
    if(((x >= 0 && x < WIDTH )
    &&  (y >= 0 && y < HEIGHT))
    && ! has_visited[y][x])
    {
        has_visited[y][x] = true;
        if(fake[y][x] != '#'
        && fake[y][x] != '*')
        {
            fake[y][x] = color;
            fillcolor_recursive(fake, color, x, y + 1, has_visited);
            fillcolor_recursive(fake, color, x + 1, y, has_visited);
            fillcolor_recursive(fake, color, x, y - 1, has_visited);
            fillcolor_recursive(fake, color, x - 1, y, has_visited);
        }
    }
}
void fillcolor(char (&fake)[HEIGHT][WIDTH], char color, int startx, int starty)
{
    bool has_visited[HEIGHT][WIDTH] = {};
    fillcolor_recursive(fake, color, startx, starty, has_visited);
}

你发布的函数有一些问题。

导致堆栈溢出,因为您没有检查是否已经查看了特定的元素。

这就是为什么我把我的解决方案分成两个函数。fillcolor是一个非递归函数,它的唯一目的是创建一个布尔值数组,表示它们对应的元素是否被访问过。

fillcolor_recursive本质上是您通过一些更改提供的函数。在您的原始函数中,您调用访问对角元素,这是不必要的。

您正在检查startxstarty是否错误地超出了界限:

if (startx+1 <= 19 && starty+1 <= 9 && startx-1 >= 0 && starty-1 >= 0)

此检查必须在检查fake[startx][starty]是否等于'#''*'之前完成。

fillcolor_recursive应该对用户隐藏