算法是隨便想的,如下:
首先迷宮初始化全部為墻
然后隨機(jī)選擇從中間一個(gè)點(diǎn)開(kāi)始,
開(kāi)始遞歸,隨機(jī)選擇方向嘗試移動(dòng),如果是墻,并且不與其他的路相通,就把墻設(shè)置成路。
使用深度優(yōu)先的方法,從新的點(diǎn)繼續(xù)遞歸,如果周?chē)繜o(wú)法走通,則回退到上次節(jié)點(diǎn),選擇其他方向。
如此一直遞歸,直到所有的點(diǎn)都探索完。最終的效果圖如下:

后來(lái)研究下別人的算法,是先假設(shè)地圖上有相間隔的點(diǎn),然后將這些點(diǎn)進(jìn)行打通,
只要這個(gè)點(diǎn)是孤立的,就可以與其他點(diǎn)連通,這樣的算法,會(huì)好看些,處理上會(huì)簡(jiǎn)單很多,
生成的圖形也沒(méi)有一個(gè)個(gè)的小塊。
照例,共享我的源碼咯:
/Files/merlinfang/maze.rar
其他人的算法,精煉很多,不過(guò)就代碼風(fēng)格實(shí)在是郁悶
// Author: Tanky Woo
// Blog: www.WuTianQi.com
// Brief: a Maze program
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
#define MAZE_MAX 50
char map[MAZE_MAX+2][MAZE_MAX+2];
const int x = 11, y = 11;
int z1, z2;
void printMaze();
void makeMaze();
int searchPath(int, int);
int main()
{
for(int i=0; i<=x*2+2; ++i)
for(int j=0; j<=y*2+2; ++j)
map[i][j] = 1;
makeMaze();
cout << "Tanky Woo" << endl;
printMaze();
}
void printMaze()
{
for(z2=1; z2<=x*2+1; z2++)
{
for(z1=1;z1<=y*2+1;z1++)
fputs(map[z2][z1]==0?" ":"█",stdout);
putchar(10);
}
cout << endl;
}
void makeMaze()
{
for(z1=0, z2=2*y+2; z1<=2*x+2; ++z1)
{
map[z1][0] = 0;
map[z1][z2] = 0;
}
for(z1=0, z2=2*x+2; z1<=2*y+2; ++z1)
{
map[0][z1] = 0;
map[z2][z1] = 0;
}
map[2][1] = 0;
map[2*x][2*y+1] = 0;
srand((unsigned)time(NULL));
searchPath(rand()%x+1, rand()%y+1);
}
int searchPath(int x, int y)
{
static int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
int zx = x*2;
int zy = y*2;
int next, turn, i;
map[zx][zy] = 0;
turn = rand()%2 ? 1 : 3;
for(i=0, next=rand()%4; i<4; ++i, next=(next+turn)%4)
if(map[zx+2*dir[next][0]][zy+2*dir[next][1]] == 1)
{
map[zx+dir[next][0]][zy+dir[next][1]] = 0;
searchPath(x+dir[next][0], y+dir[next][1]);
}
return 0;
}
posted on 2011-11-17 23:16
merlinfang 閱讀(12036)
評(píng)論(6) 編輯 收藏 引用 所屬分類(lèi):
v8