递归崩溃
Recursion Crash
我正在编写一个程序来填充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
本质上是您通过一些更改提供的函数。在您的原始函数中,您调用访问对角元素,这是不必要的。
您正在检查startx
和starty
是否错误地超出了界限:
if (startx+1 <= 19 && starty+1 <= 9 && startx-1 >= 0 && starty-1 >= 0)
此检查必须在检查fake[startx][starty]
是否等于'#'
或'*'
之前完成。
fillcolor_recursive
应该对用户隐藏
相关文章:
- 通过递归进行因子分解
- 递归函数计算序列中的平方和(并输出过程)
- 使用递归的数组的最小值.这是怎么回事
- 递归列出所有目录中的C++与Python与Ruby的性能
- 递归计数给定目录的文件和所有目录
- 如何在BST的这个简单递归实现中消除警告
- C++:正在检查LinkedList中的回文-递归方法-错误
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 递归无序映射
- 递归导致程序崩溃,但 while 循环中的相同概念不是来自C++析构函数
- 执行递归函数时 C++ 应用程序崩溃
- 不明白为什么这个简单的递归开始工作然后崩溃
- 递归函数在C++崩溃
- 这种遍历二叉树的递归方法在一些递归后崩溃!为什么?
- 使用迭代器的递归调用崩溃
- 递归插入排序崩溃几乎对于大 n
- 为什么这个递归函数会崩溃
- 为什么这个递归函数会崩溃
- 递归崩溃
- 递归二叉搜索实现崩溃.为什么