实现一下迷宫问题递归算法cpp
时间: 2023-10-03 13:07:28 浏览: 50
好的,我可以帮你实现迷宫问题的递归算法cpp。以下是代码实现:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 定义迷宫的长和宽
const int n = 6;
// 定义迷宫地图
int maze[n][n] = {
{0, 0, 1, 1, 1, 1},
{1, 0, 0, 1, 0, 1},
{1, 0, 1, 0, 0, 1},
{1, 0, 0, 0, 1, 1},
{1, 1, 1, 0, 0, 0},
{1, 1, 1, 1, 1, 0}
};
// 定义方向数组,用于控制各方向行走
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
// 递归函数,用于查找路径
bool findPath(int x, int y, vector<pair<int, int>> &path) {
// 如果已到达终点,则找到一条路径
if (x == n-1 && y == n-1) {
return true;
}
// 判断当前位置是否可通,并且是否走过
if (maze[x][y] == 0) {
// 标记已经走过
maze[x][y] = 2;
path.push_back(make_pair(x, y));
// 尝试向各个方向行走
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
// 判断当前位置是否可通,并且是否走过
if (nx >= 0 && nx < n && ny >= 0 && ny < n && maze[nx][ny] == 0) {
// 尝试向该方向行走
if (findPath(nx, ny, path)) {
return true;
}
}
}
// 如果该位置不通,则弹出该点
path.pop_back();
}
return false;
}
int main() {
vector<pair<int, int>> path;
// 从起点开始查找路径
findPath(0, 0, path);
// 输出路径
for (int i = 0; i < path.size(); i++) {
cout << "(" << path[i].first << ", " << path[i].second << ")" << endl;
}
return 0;
}
```
这里我们通过递归来实现了迷宫问题的求解,该算法相对简单,但是时间复杂度较高,如果迷宫过大,则效率可能很低。