一、迷宫满足条件

  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;
}

 

 

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐