-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_maze.cpp
87 lines (79 loc) · 2.1 KB
/
generate_maze.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include<iostream>
using namespace std;
short D[200][200] = {0}; //记录已走的路径
short Z[200][200] = {0}; //记录这里是否有墙
int nx[] = {1, 0, -1, 0};
int ny[] = {0, 1, 0, -1};
int M, N; //M-------高度 N --------------长度
void generate_maze(int x, int y); //产生一个迷宫,即打通相应的墙
void generate_wall(); //安放所有的墙
void print(); //显示迷宫
void read(); //读取长高
int main()
{
read();
generate_wall();
generate_maze(rand() % N, rand() % M);
print();
return 0;
}
void generate_maze(int x, int y){
D[x][y] = 1;
srand(time(0));
int n = 4, a[6];
for(int i = 1; i <= 4; i++){
a[i] = i;
}
random_shuffle(a+1,a+n+1);
for(int i = 0; i < 4; i++){
int xi = x + nx[a[i + 1] - 1];
int yi = y + ny[a[i + 1] - 1];
if(D[xi][yi] == 0 && xi < N && xi >= 0 && yi >= 0 && yi < M){
int mx = 2 * x + 1, my = 2 * y + 1;
if(i == 0){
Z[mx + 1][my] = 0;
}else if(i == 1){
Z[mx][my + 1] = 0;
}else if(i == 2){
Z[mx - 1][my] = 0;
}else{
Z[mx][my - 1] = 0;
}
generate_maze(xi, yi);
}
}
}
void generate_wall(){ //在偶数列和行安放墙
for(int i = 0; i < 2 * N + 1; i++){
if(i % 2 == 0){
for(int j = 0; j < 2 * M + 1; j++){
Z[i][j] = 1;
}
}
}
for(int i = 0; i < 2 * M + 1; i++){
if(i % 2 == 0){
for(int j = 0; j < 2 * N + 1; j++){
Z[j][i] = 1;
}
}
}
}
void print(){
for(int i = 0; i < 2 * N + 1; i++){
for(int j = 0; j < 2 * M + 1; j++){
if(Z[i][j]){
printf("# ");
}else{
printf(" ");
}
}
printf("\n");
}
}
void read(){
printf("please enter height of maze ");
scanf("%d", &M);
printf("please enter longth of maze ");
scanf("%d", &N);
}