走迷宫问题c++
时间: 2023-08-03 19:25:55 浏览: 61
走迷宫问题是一个经典的深度优先搜索问题。以下是一个简单的 C++ 实现示例:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 定义迷宫类型
typedef vector<vector<int>> Maze;
// 定义方向数组
const int dx[] = {0, 0, 1, -1};
const int dy[] = {1, -1, 0, 0};
// 判断是否越界
bool isValid(const Maze& maze, int x, int y) {
return x >= 0 && x < maze.size() && y >= 0 && y < maze[0].size() && maze[x][y] == 0;
}
// 深度优先搜索
bool dfs(Maze& maze, int x, int y) {
if (x == maze.size() - 1 && y == maze[0].size() - 1) { // 到达终点
return true;
}
maze[x][y] = -1; // 标记为已访问
for (int i = 0; i < 4; i++) { // 尝试四个方向
int nx = x + dx[i], ny = y + dy[i];
if (isValid(maze, nx, ny)) {
if (dfs(maze, nx, ny)) {
return true;
}
}
}
maze[x][y] = 0; // 恢复为未访问状态
return false;
}
int main() {
// 读入迷宫
int n, m;
cin >> n >> m;
Maze maze(n, vector<int>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> maze[i][j];
}
}
// 搜索
if (dfs(maze, 0, 0)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
```
在上面的实现中,我们使用一个二维向量来表示迷宫,其中 0 表示可以通过的路,1 表示障碍物。在搜索过程中,我们使用深度优先搜索来尝试四个方向,如果到达终点则返回 true,否则返回 false。搜索过程中,我们使用 -1 表示已访问状态,0 表示未访问状态。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)