我在用回溯法写一个迷宫解算器。它应该看看是否有可能解决一个给定的谜题从起点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)作为输出。有什么想法吗?
发布于 2015-07-31 03:22:31
你的迷宫'*‘只在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函数的末尾
https://stackoverflow.com/questions/31737216
复制相似问题