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.youkuaiyun.com/juzihongle1/article/details/73135920

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值