参考维基百科
1 深度优先搜索
- Start at a particular cell and call it the "exit."
- Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor:
- If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then with that neighbor as the current cell.
2 随机Kruskal算法
- Create a list of all walls, and create a set for each cell, each containing just that one cell.
- For each wall, in some random order:
- If the cells divided by this wall belong to distinct sets:
- Remove the current wall.
- Join the sets of the formerly divided cells.
- If the cells divided by this wall belong to distinct sets:
3 随机Prim算法
- Start with a grid full of walls.
- Pick a cell, mark it as part of the maze. Add the walls of the cell to the wall list.
- While there are walls in the list:
- Pick a random wall from the list. If the cell on the opposite side isn't in the maze yet:
- Make the wall a passage and mark the cell on the opposite side as part of the maze.
- Add the neighboring walls of the cell to the wall list.
- If the cell on the opposite side already was in the maze, remove the wall from the list.
- Pick a random wall from the list. If the cell on the opposite side isn't in the maze yet:
Kruskal算法和Prim算法:
一个Python源码实现:
1 import numpy as np 2 from numpy.random import random_integers as rnd 3 import matplotlib.pyplot as plt 4 5 def maze(width=81, height=51, complexity=.75, density =.75): 6 # Only odd shapes 7 shape = ((height//2)*2+1, (width//2)*2+1) 8 # Adjust complexity and density relative to maze size 9 complexity = int(complexity*(5*(shape[0]+shape[1])))10 density = int(density*(shape[0]//2*shape[1]//2))11 # Build actual maze12 Z = np.zeros(shape, dtype=bool)13 # Fill borders14 Z[0,:] = Z[-1,:] = 115 Z[:,0] = Z[:,-1] = 116 # Make isles17 for i in range(density):18 x, y = rnd(0,shape[1]//2)*2, rnd(0,shape[0]//2)*219 Z[y,x] = 120 for j in range(complexity):21 neighbours = []22 if x > 1: neighbours.append( (y,x-2) )23 if x < shape[1]-2: neighbours.append( (y,x+2) )24 if y > 1: neighbours.append( (y-2,x) )25 if y < shape[0]-2: neighbours.append( (y+2,x) )26 if len(neighbours):27 y_,x_ = neighbours[rnd(0,len(neighbours)-1)]28 if Z[y_,x_] == 0:29 Z[y_,x_] = 130 Z[y_+(y-y_)//2, x_+(x-x_)//2] = 131 x, y = x_, y_32 return Z33 34 plt.figure(figsize=(10,5))35 plt.imshow(maze(80,40),cmap=plt.cm.binary,interpolation='nearest')36 plt.xticks([]),plt.yticks([]) 37 plt.show()
运行结果如下所示: