我正在创建具有以下算法的迷宫生成器:
1)选择随机坐标,将坐标添加到路径列表
2)选择随机方向移动(上,下,左,右)
a)如果我超出了迷宫的边界,或者我移动到的坐标已经在路径中-那么请从路线列表中删除所选的路线,然后转到步骤2
b)如果我什么都不能走(路线列表为空)-然后恢复路线列表并从路径转到任意位置>
c)如果可以,请转到步骤2
重复直到访问所有可能的位置。这是程序选择坐标的一部分代码:
while len(paths) < all_positions:
if len(directions) == 0:
row, col = random.choice(paths)
directions = ['up', 'down', 'left', 'right']
else:
direction = random.choice(directions)
if direction == 'up':
if row-2 > 0 and pixels[row-2, col, 0] != 255:
row -= 2
# some other code
else:
directions.remove(direction)
# the same for down, left and right
我认为,该算法的主要缺陷是这条线row, col = random.choice(paths)
,因为当我再次被挡住(无法走到任何地方)时,我可以选择位置。因此,如果我有1000x1000的迷宫,我可以一遍又一遍地随机选择被阻止的位置。
因此,我决定创建一个列表,以供选择。所以现在我的代码如下:
while len(paths) < all_positions:
if len(directions) == 0:
if [row, col] not in blocked:
blocked.append([row, col])
nonblocked = [x for x in paths if x not in blocked]
row, col = random.choice(nonblocked)
directions = ['up', 'down', 'left', 'right']
else:
direction = random.choice(directions)
if direction == 'up':
但是现在生成迷宫所需的时间要少得多,而迷宫的位置可能更少。第一台生成器需要0.05秒的时间才能生成55x55迷宫,而0.1x则需要99x99。当第二个55x55需要1.84秒,而99x99则需要永远。代码有什么问题?