C语言迷宫生成prim算法
时间: 2023-08-31 16:12:49 浏览: 242
纯c语言迷宫源码.zip
Prim算法是一种用于生成最小生成树的算法,可以用于生成迷宫。以下是C语言实现Prim算法生成迷宫的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 11
#define COL 11
int maze[ROW][COL];
int random(int x, int y) {
return rand() % (y - x + 1) + x;
}
void init_maze() {
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
if (i == 0 || i == ROW - 1 || j == 0 || j == COL - 1) {
maze[i][j] = 1;
} else {
maze[i][j] = 0;
}
}
}
}
void print_maze() {
int i, j;
for (i = 0; i < ROW; i++) {
for (j = 0; j < COL; j++) {
if (maze[i][j] == 1) {
printf("# ");
} else {
printf(" ");
}
}
printf("\n");
}
}
void create_maze() {
int i, j, k, x, y, count = 0;
int visited[ROW * COL][2];
int visited_count = 0;
srand((unsigned)time(NULL));
for (i = 1; i < ROW - 1; i += 2) {
for (j = 1; j < COL - 1; j += 2) {
visited[count][0] = i;
visited[count][1] = j;
count++;
}
}
while (visited_count < count) {
k = random(0, count - 1);
x = visited[k][0];
y = visited[k][1];
if (maze[x][y] == 1) {
continue;
}
if (x % 2 == 0) {
if (maze[x - 1][y] == 0 && maze[x + 1][y] == 0) {
continue;
}
if (maze[x - 1][y] == 0) {
maze[x - 1][y] = 1;
visited[count][0] = x - 2;
visited[count][1] = y;
count++;
} else if (maze[x + 1][y] == 0) {
maze[x + 1][y] = 1;
visited[count][0] = x + 2;
visited[count][1] = y;
count++;
}
} else {
if (maze[x][y - 1] == 0 && maze[x][y + 1] == 0) {
continue;
}
if (maze[x][y - 1] == 0) {
maze[x][y - 1] = 1;
visited[count][0] = x;
visited[count][1] = y - 2;
count++;
} else if (maze[x][y + 1] == 0) {
maze[x][y + 1] = 1;
visited[count][0] = x;
visited[count][1] = y + 2;
count++;
}
}
maze[x][y] = 1;
visited_count++;
}
}
int main() {
init_maze();
create_maze();
print_maze();
return 0;
}
```
该代码使用Prim算法生成一个大小为11x11的迷宫,并将其打印出来。其中,init_maze()函数用于初始化迷宫,print_maze()函数用于打印迷宫,create_maze()函数用于生成迷宫,random()函数用于生成随机数。
阅读全文