我有一个问题,我的功能在1s和0s迷宫中找到路径,返回true,如果它是在该路径上或已找到退出,并返回false如果迷宫是无法解决的。每当我尝试检查我的变量的“-1”时,发现堆栈溢出错误,但是我的基本案例应该阻止这种情况发生。有没有办法使用递归更少的堆栈空间?这里是我的代码函数与递归导致堆栈溢出
bool Pathfinder::check(string& maze, stack<string>& path, int x, int y, int z)
{int checking = 0;
if ((x == 4) && (y == 4) && (z == 4))
{
path.push(this->createCoords(x, y, z));
return true;
}
else
{
if ((x + 1) < 1 || (x + 1) > columns)
{
return false;
}
if ((y + 1) < 1 || (y + 1) > rows)
{
return false;
}
if ((z + 1) < 1 || (z + 1) > floors)
{
return false;
}
if ((x < 0) || (y < 0) || (z < 0))
{
return false;
}
if (this->getValue(maze, x, y, z) == 1)
{
this->setValue(maze, x, y, z, 2);
}
else
{
return false;
}
}
if (this->check(maze, path, x + 1, y, z) ||
this->check(maze, path, x, y + 1, z) ||
this->check(maze, path, x, y, z + 1))
{
checking++;
}
if (this->check(maze, path, x - 1, y, z) && checking == 1) //Overflow error comes from here
{
checking++;
}
if (this->check(maze, path, x, y - 1, z) && checking == 2)
{
checking++;
}
if (this->check(maze, path, x, y, z - 1) && checking == 3)
{
path.push(this->createCoords(x, y, z));
return true;
}
return false;
}
这听起来像你的功能永远不会停止递归。您是否考虑过使用调试器来追踪代码或添加一些日志记录,以便了解实际发生的情况? –
这不是问题,但前五个if语句的括号太多了。你不需要任何内在的东西。 –
*有没有办法使用递归较少的堆栈空间?* - 到目前为止,您还没有证明问题是堆栈空间。如果它只是你的代码中的一个错误,或者你的逻辑错误导致堆栈溢出,而不仅仅是你是一个迷宫?另外,你测试了哪些数据?如果您还没有这样做,我建议您使用更小的迷宫,以确保这不仅仅是一个错误。 – PaulMcKenzie