我有一个二维数组,我想用它来创建一个迷宫。
每个值可以是0或1,其中0表示有墙,1表示有房间。现在我需要一个算法来在该数组中创建一个“路径”。
例如,空白数组如下所示:
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
“路径”的一个例子是:
0 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0
0 0 0 0 1 0 1 0
0 0 0 1 1 1 1 0
0 0 0 1 0 1 0 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
基本上归结为:
1)一切都是0
2)我有一个随机起点,它是1
3)从那时起,我需要制作随机相邻值1
。但是:永远不应该有一个4个或更多相邻字段的正方形是1
AND:我不想要一个线性路径,我希望它是一个迷宫
(并不是所有阵列都必须用于迷宫。事实上,如果我可以说我希望在该阵列中有一定数量(比如20或50)的房间,那将会很酷。
我是否可以使用任何好的算法或想法(特别是我的列表中的#3)?
答案 0 :(得分:3)
递归回溯程序可以做到这一点。
algorithm gen-maze(pos):
set pos to 1
build a list of neighboring positions
randomly shuffle this list
for each neighbor n of pos in random order:
if n is 0 and setting it to 1 doesn't create a square:
gen-maze(n)
从随机位置启动此算法。
要获得解释,请阅读Wikipedia article about depth-first search并确保观看animation。