三种迷宫生成算法

本文探讨了三种迷宫生成算法:递归回溯法,通过递归方式创建迷宫,但可能引发栈溢出问题;递归分割法,提供了一种不同的迷宫构造思路;以及Eller算法,通过特定步骤打印出迷宫。文章引用了相关资源,深入解析每种算法的实现细节。
摘要由CSDN通过智能技术生成

三种迷宫生成算法

递归回溯:

	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
  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值