[英]Backtracking maze
我正在尝试使用回溯来编写迷宫求解器。 它应该查看是否有可能解决从起点S到终点E的给定难题。伪代码可以在此处的链接中看到。 我的实现如下所示:
const int N = 8; // global var
bool exploreMaze(char maze[][N], int x, int y)
{
if(y >= 8 || y < 0 || x >= 7 || x < 0) // null char at end of each 1d array
return false;
if(maze[x][y] == '*')
return false;
if(maze[x][y] == 'E')
return true;
maze[x][y] = '*'; // set grid to '*' as to not loop infinitely
if(exploreMaze(maze, x + 1, y))
{
cout << "up" << ", ";
return true;
}
if(exploreMaze(maze, x - 1, y))
{
cout << "down" << ", ";
return true;
}
if(exploreMaze(maze, x, y - 1))
{
cout << "left" << ", ";
return true;
}
if(exploreMaze(maze, x, y + 1))
{
cout << "right" << ", ";
return true;
}
return false;
}
bool isMazeSolvable(char maze[][N])
{
int startX = -1, startY = -1;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if(maze[i][j] == 'S')
startX = i;
startY = j;
}
}
if(startX == -1)
return false;
return exploreMaze(maze, startX, startY);
}
int main()
{
char maze[N][N] = {"*******", " S ", "*******", " E ", "*******",
"*******", "*******", "*******"};
cout << isMazeSolvable(maze);
return 0;
}
我在main中测试的数组绝对应该没有解决方案,但是以某种方式我得到1(true)作为输出。 有任何想法吗?
您的迷宫“ *”仅在Y方向上初始化为7个字符,但是您的迷宫助步器签出为8个字符。 这使它可以在墙的末端走动。
我添加了快速迷宫打印功能,并将exploreMaze
更改为“。”。 它走到哪里。 提供以下输出:
Initial maze:
*******
S
*******
E
*******
*******
*******
*******
left, left, left, left, left, up, up, right, right, right, right, right, right,
1
After explore:
*******
.......
*******.
E.....
*******
*******
*******
*******
解决方案:更改初始化程序以使用8个字符的墙,或者更改exploreMaze
函数以在Y方向上仅显示7个字符。
另请注意:您没有执行迷宫求解器的“回溯”部分,因为您标记了您曾经去过的地方,但是在清理递归时不会清除路径。 加
maze[x][y] = ' '; // Clear the grid so we can try this spot again in another recursion
到exploreMaze
函数的结尾
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.