用c语言写迷宫
时间: 2023-08-16 19:04:26 浏览: 43
好的,我可以为您提供一个简单的迷宫生成代码,使用C语言编写。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 10
#define COL 10
#define WALL 1
#define PATH 0
void generate_maze(int maze[ROW][COL], int row, int col) {
// 初始化迷宫
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
maze[i][j] = WALL;
}
}
// 随机生成起始点
srand((unsigned int) time(NULL));
int start_row = rand() % row;
int start_col = rand() % col;
maze[start_row][start_col] = PATH;
// 递归生成迷宫
int direction[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // 上下左右四个方向
int rand_dir[4] = {0, 1, 2, 3}; // 随机打乱方向
for (int i = 0; i < 4; i++) {
int j = rand() % 4;
int temp = rand_dir[i];
rand_dir[i] = rand_dir[j];
rand_dir[j] = temp;
}
for (int i = 0; i < 4; i++) {
int next_row = start_row + direction[rand_dir[i]][0] * 2;
int next_col = start_col + direction[rand_dir[i]][1] * 2;
if (next_row >= 0 && next_row < row && next_col >= 0 && next_col < col && maze[next_row][next_col] == WALL) {
maze[start_row + direction[rand_dir[i]][0]][start_col + direction[rand_dir[i]][1]] = PATH;
maze[next_row][next_col] = PATH;
generate_maze(maze, row, col);
}
}
}
void print_maze(int maze[ROW][COL], int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (maze[i][j] == WALL) {
printf("■ ");
} else {
printf("□ ");
}
}
printf("\n");
}
}
int main() {
int maze[ROW][COL];
generate_maze(maze, ROW, COL);
print_maze(maze, ROW, COL);
return 0;
}
```
该代码使用递归方式生成迷宫,随机生成起始点,并随机打乱方向。最终输出迷宫的图形。您可以根据实际需要进行修改和完善。