[英]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.