写一段生成随机迷宫代码
时间: 2023-04-03 20:01:43 浏览: 99
C++随机生成迷宫算法
以下是一段生成随机迷宫的代码:
#include <iostream>
#include <vector>
#include <stack>
#include <cstdlib>
#include <ctime>
using namespace std;
const int N = 20; // 迷宫大小
const int WALL = 1; // 墙
const int PATH = ; // 路径
int maze[N][N]; // 迷宫数组
// 初始化迷宫
void initMaze() {
for (int i = ; i < N; i++) {
for (int j = ; j < N; j++) {
maze[i][j] = WALL;
}
}
}
// 打印迷宫
void printMaze() {
for (int i = ; i < N; i++) {
for (int j = ; j < N; j++) {
if (maze[i][j] == WALL) {
cout << "# ";
} else {
cout << " ";
}
}
cout << endl;
}
}
// 随机生成迷宫
void generateMaze() {
srand(time(NULL)); // 初始化随机数种子
stack<pair<int, int>> s; // 存储已访问的格子
int x = rand() % N, y = rand() % N; // 随机选取起点
s.push(make_pair(x, y));
while (!s.empty()) {
pair<int, int> p = s.top();
s.pop();
x = p.first, y = p.second;
if (maze[x][y] == PATH) {
continue;
}
maze[x][y] = PATH;
vector<pair<int, int>> neighbors; // 存储未访问的邻居
if (x > && maze[x - 1][y] == WALL) {
neighbors.push_back(make_pair(x - 1, y));
}
if (x < N - 1 && maze[x + 1][y] == WALL) {
neighbors.push_back(make_pair(x + 1, y));
}
if (y > && maze[x][y - 1] == WALL) {
neighbors.push_back(make_pair(x, y - 1));
}
if (y < N - 1 && maze[x][y + 1] == WALL) {
neighbors.push_back(make_pair(x, y + 1));
}
if (!neighbors.empty()) {
s.push(p);
int r = rand() % neighbors.size();
s.push(neighbors[r]);
}
}
}
int main() {
initMaze();
generateMaze();
printMaze();
return ;
}
阅读全文