迷宫问题数据结构C++代码,迷宫随机生成
时间: 2023-08-10 20:43:39 浏览: 277
以下是一个简单的迷宫问题的数据结构C++代码,包括迷宫随机生成的部分:
```c++
#include <iostream>
#include <vector>
#include <stack>
#include <cstdlib>
#include <ctime>
using namespace std;
// 定义迷宫单元格类型
enum class MazeCellType {
Wall,
Path,
Start,
End
};
// 定义迷宫单元格
struct MazeCell {
MazeCellType type;
bool visited;
};
// 定义迷宫类型
typedef vector<vector<MazeCell>> Maze;
// 随机生成迷宫
void generateMaze(Maze& maze, int width, int height) {
// 初始化迷宫
maze.clear();
maze.resize(height, vector<MazeCell>(width, {MazeCellType::Wall, false}));
// 随机生成起点和终点
srand(time(nullptr));
int start_x = rand() % width;
int start_y = rand() % height;
int end_x = rand() % width;
int end_y = rand() % height;
maze[start_y][start_x].type = MazeCellType::Start;
maze[end_y][end_x].type = MazeCellType::End;
// 随机生成迷宫路径
stack<pair<int, int>> path;
path.push({start_x, start_y});
maze[start_y][start_x].visited = true;
while (!path.empty()) {
int x = path.top().first;
int y = path.top().second;
vector<int> directions;
if (x-1 >= 0 && !maze[y][x-1].visited) directions.push_back(0);
if (x+1 < width && !maze[y][x+1].visited) directions.push_back(1);
if (y-1 >= 0 && !maze[y-1][x].visited) directions.push_back(2);
if (y+1 < height && !maze[y+1][x].visited) directions.push_back(3);
if (directions.empty()) {
path.pop();
} else {
int direction = directions[rand() % directions.size()];
if (direction == 0) {
maze[y][x-1].visited = true;
maze[y][x-1].type = MazeCellType::Path;
path.push({x-1, y});
} else if (direction == 1) {
maze[y][x+1].visited = true;
maze[y][x+1].type = MazeCellType::Path;
path.push({x+1, y});
} else if (direction == 2) {
maze[y-1][x].visited = true;
maze[y-1][x].type = MazeCellType::Path;
path.push({x, y-1});
} else if (direction == 3) {
maze[y+1][x].visited = true;
maze[y+1][x].type = MazeCellType::Path;
path.push({x, y+1});
}
}
}
}
// 输出迷宫
void printMaze(const Maze& maze) {
for (int i = 0; i < maze.size(); i++) {
for (int j = 0; j < maze[i].size(); j++) {
if (maze[i][j].type == MazeCellType::Wall) {
cout << "#";
} else if (maze[i][j].type == MazeCellType::Path) {
cout << ".";
} else if (maze[i][j].type == MazeCellType::Start) {
cout << "S";
} else if (maze[i][j].type == MazeCellType::End) {
cout << "E";
}
}
cout << endl;
}
}
int main() {
// 生成迷宫并输出
Maze maze;
int width = 10;
int height = 10;
generateMaze(maze, width, height);
printMaze(maze);
return 0;
}
```
这个代码使用了一个二维的 vector 来表示迷宫,随机生成起点和终点,然后使用随机深度优先搜索算法来生成迷宫路径。最后输出迷宫的时候,将不同类型的迷宫单元格用不同的字符表示。
阅读全文