dfs生成迷宫

一、迷宫随机生成算法 : dfs

import numpy as np
import random
from matplotlib import pyplot as plt
import matplotlib.cm as cm
num_rows = 10
num_cols = 10

# M = [L,U,R,D,VIS]
M = []
r = 0
c = 0

M = np.zeros((num_rows,num_cols,5),dtype=np.uint8)
image = np.zeros((num_rows * 10,num_cols * 10),dtype = np.uint8)

st = []
st.append([r,c])

while st:
	M[r,c,4] = 1
	dirc = []
	if c > 0 and M[r,c-1,4] == 0:
		dirc.append('L')
	if r > 0 and M[r-1,c,4] == 0:
		dirc.append('U')
	if c < num_cols - 1 and M[r,c+1,4] == 0:
		dirc.append('R')
	if r < num_rows - 1 and M[r+1,c,4] == 0:
		dirc.append('D')

	if len(dirc):
		move_dir = random.choice(dirc)
		if move_dir == 'L':
			M[r,c,0] = 1
			c -= 1
			M[r,c,2] =1
		if move_dir == 'U':
			M[r,c,1] = 1
			r -= 1
			M[r,c,3] = 1
		if move_dir == 'R':
			M[r,c,2] = 1
			c += 1
			M[r,c,0] = 1
		if move_dir == 'D':
			M[r,c,3] = 1
			r += 1
			M[r,c,1] = 1
		st.append([r,c])

	else:
		r,c = st.pop()

M[0,0,0] =1
M[num_rows -1,num_cols-1,2] =1 



for row in range(0,num_rows):
	for col in range(0,num_cols):
		cell_data = M[row][col]
		for i in range(row * 10 +2,row*10+8):
			image[i,range(col*10 + 2,col*10+8)] = 255
		if cell_data[0] == 1:
			image[range(row*10+2,row*10+8),col*10]=255
			image[range(row*10+2,row*10+8),col*10 + 1]=255
		if cell_data[1] == 1:
			image[row*10,range(col*10+2,col*10+8)] =255
			image[row*10+1,range(col*10+2,col*10+8)] =255
		if cell_data[2] == 1:
			image[range(row*10+2,row*10+8),col*10+8]=255
			image[range(row*10+2,row*10+8),col*10+9]=255
		if cell_data[3] == 1:
			image[row*10 + 8,range(col*10+2,col*10+8)] =255
			image[row*10 + 9,range(col*10+2,col*10+8)] =255

plt.imshow(image,cmap = cm.Greys_r, interpolation='none')
plt.show()

参考:https://blog.csdn.net/juzihongle1/article/details/73135920

你可能感兴趣的:(算法,python)