三种迷宫生成算法
递归回溯:
static char block = 'x';
static char way = ' ';
enum DIRECTION {
UP, DOWN, LEFT, RIGHT
};
static List<String> history = new ArrayList<String>();
static Random ran = new Random(System.currentTimeMillis());
/**
*
* 递归回溯(核心思想为打洞)
* 在迷宫中任意选择一个点
* 从这个点朝任意一个方向挖洞,打通下一个点(已走过的点不能被打通)
* 从下个点继续打洞,直到无法某个点无法打通到下个点时,回退到上个点
* 直到回退到初始点时,迷宫完成
*
*/
public static char[][] createMaze() {
int size = 20;
char[][] maze = new char[size * 2 - 1][size * 2 - 1];
for (int i = 0; i < size * 2 - 1; i++) {
for (int j = 0; j < size * 2 - 1; j++) {
if (i % 2 == 0 && j % 2 == 0) {
maze[i][j] = way;
} else {
maze[i][j] = block;
}
}
}
Random ran = new Random(System.currentTimeMillis());
int x = ran.nextInt(size), y = ran.nextInt(size);
history.clear();
digHole(maze, x, y);
return maze;
}
private static void digHole(char[][] maze, int x, int y) {
int size = (maze.length + 1) / 2;
if (x < 0 || y < 0 || x >= size || y >= size) {
return;
}
Set<DIRECTION> dirList = new HashSet<DIRECTION>();
int dir = ran.nextInt(4);
history.add(x + "," + y);
while (dirList.size() < 4) {
// 选择一个方向
while (dirList.contains(DIRECTION.values()[dir])) {
dir = (dir >= 3 ? 0 : dir + 1);
}
int nextX = -1, nextY = -1;
// 定位下个点
DIRECTION direction = DIRECTION.values()[dir];
switch (direction) {
case UP:
nextX = x - 1;
nextY = y;
break;
case DOWN:
nextX = x + 1;
nextY = y;
break;
case LEFT:
nextX = x;
nextY = y - 1;
break;
case RIGHT:
nextX = x;
nextY = y + 1;
break;
}
// 挖洞
if (nextX >= 0 && nextX < size && nextY >= 0 && nextY < size
&& !history.contains(nextX + "," + nextY)) {
maze[nextX * 2][nextY * 2] = way;
try {
switch (direction) {
case UP:
maze[nextX * 2 + 1][nextY * 2] = way;
break;
case DOWN:
maze[nextX * 2 - 1][nextY * 2] = way;
break;
case LEFT:
maze[nextX * 2][nextY * 2 + 1] = way;
break;
case RIGHT:
maze[nextX * 2][nextY * 2 - 1] = way;
br