s解决迷宫问题c++
时间: 2024-09-09 09:01:15 浏览: 40
解决迷宫问题是一个经典的计算机科学问题,通常通过深度优先搜索(Depth First Search, DFS)或广度优先搜索(Breadth First Search, BFS)算法来实现。在C++中,可以使用数组或二维字符矩阵来表示迷宫,其中0代表空地,1代表墙壁。
以下是使用DFS的一个基本思路:
```cpp
void dfs(int maze[][N], int start_row, int start_col, bool visited[]) {
// 验证当前位置是否有效
if (start_row < 0 || start_row >= N || start_col < 0 || start_col >= N || maze[start_row][start_col] == 1 || visited[start_row][start_col]) return;
// 标记当前位置已访问并递归遍历相邻未访问位置
visited[start_row][start_col] = true;
if (start_row > 0 && maze[start_row - 1][start_col] != 1) dfs(maze, start_row - 1, start_col, visited);
if (start_col < N - 1 && maze[start_row][start_col + 1] != 1) dfs(maze, start_row, start_col + 1, visited);
if (start_row < N - 1 && maze[start_row + 1][start_col] != 1) dfs(maze, start_row + 1, start_col, visited);
if (start_col > 0 && maze[start_row][start_col - 1] != 1) dfs(maze, start_row, start_col - 1, visited);
// 当回溯到起点时,标记终点
if (start_row == end_row && start_col == end_col) {
cout << "Path found!" << endl;
}
}
```
你可以调用`dfs`函数,传递迷宫、起始位置和一个布尔矩阵`visited`来跟踪已经访问过的节点,找到从起点到终点的路径。
阅读全文
相关推荐


















