在C++中为随机迷宫创建单元格或网格,可以使用以下步骤:
以下是一个简单的C++代码示例,用于创建一个随机迷宫:
#include<iostream>
#include<vector>
#include<random>
#include <ctime>
using namespace std;
const int ROWS = 10;
const int COLS = 10;
struct Cell {
bool visited;
vector<Cell*> neighbors;
};
int main() {
srand(time(NULL));
vector<vector<Cell>> maze(ROWS, vector<Cell>(COLS));
// Initialize maze cells
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
maze[row][col].visited = false;
}
}
// Generate random maze
int row = rand() % ROWS;
int col = rand() % COLS;
maze[row][col].visited = true;
while (true) {
int num_neighbors = 0;
vector<Cell*> neighbors;
// Check neighbors
if (row > 0 && !maze[row - 1][col].visited) {
num_neighbors++;
neighbors.push_back(&maze[row - 1][col]);
}
if (row < ROWS - 1 && !maze[row + 1][col].visited) {
num_neighbors++;
neighbors.push_back(&maze[row + 1][col]);
}
if (col > 0 && !maze[row][col - 1].visited) {
num_neighbors++;
neighbors.push_back(&maze[row][col - 1]);
}
if (col < COLS - 1 && !maze[row][col + 1].visited) {
num_neighbors++;
neighbors.push_back(&maze[row][col + 1]);
}
// If all neighbors have been visited, backtrack
if (num_neighbors == 0) {
bool found = false;
for (int r = 0; r < ROWS && !found; r++) {
for (int c = 0; c < COLS && !found; c++) {
if (!maze[r][c].visited) {
row = r;
col = c;
found = true;
}
}
}
if (!found) {
break;
}
}
// Choose a random neighbor
int index = rand() % num_neighbors;
Cell* next_cell = neighbors[index];
next_cell->visited = true;
// Connect current cell to chosen neighbor
maze[row][col].neighbors.push_back(next_cell);
next_cell->neighbors.push_back(&maze[row][col]);
// Move to next cell
row = next_cell - &maze[0][0];
col = next_cell - &maze[0][0];
}
// Print maze
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
cout << (maze[row][col].visited ? "X" : " ");
}
cout<< endl;
}
return 0;
}
这个代码示例使用了一个二维数组来存储迷宫的单元格,并使用随机算法来生成迷宫。每个单元格都有一个布尔值来表示是否已被访问,以及一个邻居列表来表示与其相邻的单元格。在生成迷宫时,从一个随机单元格开始,随机选择一个相邻的未访问单元格,并将其标记为已访问。然后,将当前单元格与选择的单元格连接起来,并将选择的单元格作为下一个单元格。重复这个过程,直到所有单元格都被访问。最后,打印出迷宫。
领取专属 10元无门槛券
手把手带您无忧上云