[英]Recursively finding a path through a maze c++
I have been working to solve this for hours now. 我已经努力解决了几个小时。 I am looking to use a recursive function to solve a maze that is given by the user input.
我正在寻找使用递归函数来解决由用户输入给出的迷宫。 The structure of the maze looks like this:
迷宫的结构如下所示:
##########
# ### #
# # #
# #
# 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;
}
This is my recursive method above and the "o" marks a solution. 这是我上面的递归方法,“ o”标记为解决方案。 Every time I run the program I am facing an infinite recursion and get the error
每次运行程序时,我都面临无限递归并得到错误
"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."
“”在ProjectName.exe中的0x002396DA处引发异常:0xC0000005:访问冲突写入位置0x000A0FFC“和”在ProjectName.exe中的0x002396DA处存在未处理的异常:0xC0000005:访问冲突写入位置为0x000A0FFC。
Add the missing case: 添加缺少的情况:
if (maze[currR][currC] == "+")
return false; // Already visited
You are tracing back the already visited trail and making no use of '+'
marks traced by you causing the infinite recursion and the iterations are not converging. 您正在回溯已访问的路径,并且不使用导致无限递归且迭代未收敛的
'+'
标记。
You never checked if you are looking at a spot that you have already explored before. 您从未检查过您是否正在探索的景点。 You set the current path to "+"s, but you never actually checked for it in the function.
您将当前路径设置为“ +”,但从未在函数中实际检查过它。 Add an if statement to have the function not recurse if the current position is marked "+".
如果当前位置标记为“ +”,则添加一条if语句以使函数不递归。
By the way, you can speed up your algorithm a lot by not setting the path back to " " when you backtrack so that once a position is explored you don't ever come back to it. 顺便说一句,您可以通过在回溯时不将路径设置回“”来大大提高算法的效率,这样一经探索位置,您就永远不会回到该位置。 This works because it does not matter where you came from, it only matters if there is a path starting from that position.
之所以有效,是因为无论您来自何处,都只有在从该位置开始的路径时才重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.