建议先看这篇:深度优先算法走迷宫
生成迷宫采用深度优先破墙法
1、用数组定义一个待破墙的迷宫
1代表墙,0代表空房间
生成迷宫,即把墙打破,让每个房间连接起来
int MAP[7][7] = {
0,1,0,1,0,1,0,
1,1,1,1,1,1,1,
0,1,0,1,0,1,0,
1,1,1,1,1,1,1,
0,1,0,1,0,1,0,
1,1,1,1,1,1,1,
0,1,0,1,0,1,0
};
即
2、定义一个辅助数组(目的是防止超越地图数组下标越界访问和记录遍历信息)
比原数组大了4行4列,相当于加了一个外墙
int isFind[11][11] = {
1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,
1,1,0,1,0,1,0,1,0,1,1,
1,1,1,1,1,1,1,1,1,1,1,
1,1,0,1,0,1,0,1,0,1,1,
1,1,1,1,1,1,1,1,1,1,1,
1,1,0,1,0,1,0,1,0,1,1,
1,1,1,1,1,1,1,1,1,1,1,
1,1,0,1,0,1,0,1,0,1,1,
1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,
};
3、循环结束的条件
在深度优先算法走迷宫里,循环结束的条件遍历到终点
而现在生成迷宫循环结束的条件是遍历完地图上的所有节点
源代码
此代码只是一个简易模板,还有可以优化的地方
#include <iostream>
#include <stack>
using namespace std;
struct Point {
int row;
int col;
};
int main() {
int MAP[7][7] = {
0,1,0,1,0,1,0,
1,1,1,1,1,1,1,
0,1,0,1,0,1,0,
1,1,1,1,1,1,1,
0,1,0,1,0,1,0,
1,1,1,1,1,1,1,
0,1,0,1,0,1,0
};
int isFind[11][11] = {
1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,
1,1,0,1,0,1,0,1,0,1,1,
1,1,1,1,1,1,1,1,1,1,1,
1,1,0,1,0,1,0,1,0,1,1,
1,1,1,1,1,1,1,1,1,1,1,
1,1,0,1,0,1,0,1,0,1,1,
1,1,1,1,1,1,1,1,1,1,1,
1,1,0,1,0,1,0,1,0,1,1,
1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,
};
stack<Point> ms;
Point curP = { 2,2 };//isfind地图对应在原地图上的起始点
ms.push(curP);
int direction = 0;
srand((unsigned)time(NULL));
while (1) {
//结束循环条件:遍历完了
int n = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (isFind[i][j] == 0)n++;
}
}
if (n == 0)break;
//走的方向是随机的 0123上左下右
direction = rand() % 4;
//退栈条件是走到死胡同,死胡同是上下左右都走过了
if (isFind[curP.row - 2][curP.col] == 1 && isFind[curP.row][curP.col - 2] == 1 &&
isFind[curP.row + 2][curP.col] == 1 && isFind[curP.row][curP.col + 2] == 1)
{
ms.pop();
curP = ms.top();
}
if (direction == 0 && isFind[curP.row - 2][curP.col] == 0) {//向上走并且上面未被遍历或者边界墙
MAP[curP.row - 1 - 2][curP.col - 2] = 0;//打破墙,原地图比isfind地图小二
isFind[curP.row - 2][curP.col] = 1;//记录走过
curP.row -= 2;
ms.push(curP);
}
else if (direction == 1 && isFind[curP.row][curP.col - 2] == 0) {
MAP[curP.row - 2][curP.col - 1 - 2] = 0;
isFind[curP.row][curP.col - 2] = 1;
curP.col -= 2;
ms.push(curP);
}
else if (direction == 2 && isFind[curP.row + 2][curP.col] == 0) {
MAP[curP.row + 1 - 2][curP.col - 2] = 0;
isFind[curP.row + 2][curP.col] = 1;
curP.row += 2;
ms.push(curP);
}
else if (direction == 3 && isFind[curP.row][curP.col + 2] == 0) {
MAP[curP.row - 2][curP.col + 1 - 2] = 0;
isFind[curP.row][curP.col + 2] = 1;
curP.col += 2;
ms.push(curP);
}
}
cout << "生成地图:" << endl;
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
cout << MAP[i][j] << "\t";
}
cout << endl<<endl;
}
}
生成结果,运行两次,结果是不一样的,符合随机性