gpt4 book ai didi

c++ - 递归地找到一条穿过迷宫的路径 C++

转载 作者:太空宇宙 更新时间:2023-11-04 15:59:08 24 4
gpt4 key购买 nike

几个小时以来,我一直在努力解决这个问题。我正在寻找使用递归函数来解决用户输入给出的迷宫。迷宫的结构是这样的:

##########          
# ### #
# # #
# #
# o #
# #
##########

bool searchMaze(int currR, int currC)
if (currR > (rows-1) || currC > (columns-1) || currR < 0 || currC < 0)
return false;
if (maze[currR][currC] == "o")
return true;
if (maze[currR][currC] == "#")
return false;
maze[currR][currC] = "+";

if (searchMaze((currR - 1), currC) == true)
{
return true;
}
if (searchMaze(currR, (currC + 1)) == true)
{
return true;
}

if (searchMaze((currR + 1), currC) == true)
{
return true;
}
if (searchMaze(currR, (currC - 1)) == true)
{
return true;
}
maze[currR][currC] = " ";
return false;
}

这是我上面的递归方法,“o”表示一个解决方案。每次运行程序时,我都会面临无限递归并得到错误

"Exception thrown at 0x002396DA in projectName.exe: 0xC0000005: Access violation writing location 0x000A0FFC" and "Unhandled exception at 0x002396DA in projectName.exe: 0xC0000005: Access violation writing location 0x000A0FFC."

最佳答案

添加缺失的案例:

if (maze[currR][currC] == "+")
return false; // Already visited

您正在追溯已经访问过的踪迹并且没有使用您追踪的 '+' 标记导致无限递归并且迭代不收敛。

关于c++ - 递归地找到一条穿过迷宫的路径 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48739863/

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