[英]DFS algorithm maze generator
I'm trying to use the DFS algo to create a maze in ASCII ('#' represents a wall and ' ' a free space) that has as start the upper left corner and as exit the lower right corner. 我正在尝试使用DFS算法在ASCII中创建一个迷宫(“#”代表一堵墙,而“”是一个自由空间),该迷宫的左上角为起点,右下角为出口。 The problem is the maze starts its creation and then it's blocked because all its neighbors have been already visited.
问题在于迷宫开始创建,然后由于所有邻居都已被访问而被阻止。
I start at the upper left corner, mark the cell as visited and put a ' ' (it represents a free space), then I chose randomly a neighbor of the cell and I do the same. 我从左上角开始,将单元格标记为已访问,然后放置“”(它代表一个自由空间),然后随机选择该单元格的邻居,然后执行相同的操作。 However I put this in a while loop and I'm sure this isn't the good idea.
但是我把它放在了while循环中,我确定这不是个好主意。
Here my attempt of the DFS : 这是我对DFS的尝试:
int generation(t_maze *maze, int pos_y, int pos_x)
{
int dest;
maze->maze[pos_y][pos_x] = ' ';
maze->visited[pos_y][pos_x] = '1';
while (maze->maze[maze->height - 1][maze->width - 1] == '#')
{
if ((dest = my_rand(1, 4)) == 1 && pos_y - 1 >= 0 && maze->visited[pos_y - 1][pos_x] == '0')
generation(maze, pos_y - 1, pos_x);
else if (dest == 2 && pos_x + 1 < maze->width && maze->visited[pos_y][pos_x + 1] == '0')
generation(maze, pos_y, pos_x + 1);
else if (dest == 3 && pos_y + 1 < maze->height && maze->visited[pos_y + 1][pos_x] == '0')
generation(maze, pos_y + 1, pos_x);
else if (dest == 4 && pos_x - 1 >= 0 && maze->visited[pos_y][pos_x - 1] == '0')
generation(maze, pos_y, pos_x - 1);
my_showtab(maze->maze); //it prints the 2d array
usleep(50000);
}
typedef struct s_maze
{
int width;
int height;
char **maze;
char **visited;
} t_maze;
In the structure, width is the width of the maze height is the height of the maze maze is a 2D array that is supposed to be filled with ' ' and '#' visited is a 2D array with 0 and 1, 0 : unvisited, 1 : visited 在结构中,width是迷宫的宽度height是迷宫的高度迷宫是应该填充为''的2D数组,而'#'则是0和1的2D数组,0:未访问, 1:已访问
I want to have a maze like this (little example) 我想要一个这样的迷宫(小例子)
########
# #
## #
# #
#######
Your code builds one path as it always goes to only one next cell. 您的代码会建立一条路径,因为它始终只会进入下一个单元格。 That's not a dfs.
那不是dfs。 You could do it like that:
您可以这样做:
def dfs(x, y):
visited[x][y] = true
maze[x][y] = ' '
next_cell = random unvisited neighbors of (x, y):
dfs(next_cell.x, next_cell.y)
The point is: you need to backtrack at some point (it's convenient to use recursion for it). 关键是:您需要在某个时候回溯(使用递归很方便)。 A single path won't look the way you want (it may also get stuck and never reach the exit).
一条路径不会看起来像您想要的样子(它也可能卡住并且永远不会到达出口)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.