Maze generator(迷宫生成器)

一、迷宫满足条件

  1. There are no circles in the maze, which means all roads in the maze lead to an dead end or to the exit.
  2. There are no wall blocks in the maze. Each wall is 1 unit in width, each road is also 1 unit in width.

二、具体流程

  1. if this cell is out of boundary, do not dig it, return to last step
  2. if this cell is already digged, do not dig it again, return to last step
  3. if there are more than 1 of its 4 neighbor cells are digged, do not dig it, return to last step (since it will cause circles in path)
  4. else dig it. and move to this cell, jump to step 1.
map = [][] # initialize the map with full of walls
for each (i, j) cell in map:
  DFS(i,j)

def DFS(i, j):
  if i, j is out of boundary:
    return
  if (i,j) is visited:
    return 
  if number of visited neighbors of (i, j) > 1:
    return 
  mark cell as visited
  for each neighbor (ni, nj) of cell(random order):
    DFS(ni, nj)

三、代码

#include<iostream>
#include<ctime>
#include<random>
using namespace std;

const int WIDTH = 20;
const int HEIGHT = 20;
class Solution {
private:
	char map[HEIGHT][WIDTH];
	int dir[4][2] = { {1,0},{0,1},{-1,0},{0,-1} };
public:
	void init() {
		for (int i = 0; i < HEIGHT; i++) {
			for (int j = 0; j < WIDTH; j++) {
				map[i][j] = '#';
			}
		}
		dfs(0, 0);
	}
	void dfs(int x, int y) {
		if (x < 0 || x >= HEIGHT || y < 0 || y >= WIDTH)
			return;
		if (map[x][y] == ' ')
			return;
		if (visitedNeighborNumber(x,y) > 1)
			return;
		map[x][y] = ' ';
		shuffle();
		for (int i = 0; i < 4; i++) {
			int tx = x + dir[i][1];
			int ty = y + dir[i][0];
			dfs(tx, ty);
		}
	}
	void shuffle() {
		std::default_random_engine e(time(0));
		std::uniform_int_distribution<int> idx(0,3);//闭区间
		for (int i = 0; i < 4; i++) {
			swap(dir[i], dir[idx(e)]);
		}
	}
	int visitedNeighborNumber(int x,int y) {
		int cnt = 0;
		for (int i = 0; i < 4; i++) {
			int tx = x + dir[i][1];
			int ty = y + dir[i][0];
			if (tx < 0 || tx >= HEIGHT || ty < 0 || ty >= WIDTH)
				continue;
			if (map[tx][ty] == ' ')
				cnt++;
		}
		return cnt;
	}
	void Show() {
		for (int i = 0; i < HEIGHT; i++) {
			for (int j = 0; j < WIDTH; j++) {
				cout << map[i][j] << " ";
			}
			cout << "\n";
		}
	}
};
int main() {
	Solution s = Solution();
	s.init();
	s.Show();
	return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值