import numpy as np
import matplotlib.pyplot as plt
class path:
def __init__(self, x, y, order, direction):
self.x = x
self.y = y
self.order = order
self.direction = direction
def changeDirection(self, direction):
if(direction == 3):
self.changeDirection_x(1)
elif(direction == 2):
self.changeDirection_y(-1)
elif(direction == 1):
self.changeDirection_x(-1)
else:
pass
def changeDirection_x(self, direction): # direction = 1 || -1
self.x = self.x + direction
def changeDirection_y(self, direction): # direction = 1 || -1
self.y = self.y + direction
def changeOrder(self, order):
self.order = order
# 构造迷宫
def initMaze():
a = np.zeros((10, 10))
# 墙
wall = 100
a[:, 0] = wall
a[:, -1] = wall
a[0, :] = wall
a[-1, :] = wall
a[1, 3] = wall
a[1, 7] = wall
a[2, 3] = wall
a[2, 7] = wall
a[3, 5] = wall
a[3, 6] = wall
a[4, 2] = wall
a[4, 4] = wall
a[4, 4] = wall
a[5, 4] = wall
a[6, 2] = wall
a[6, 6] = wall
a[7, 2] = a[7, 3]= a[7, 4] = a[7, 6] = a[7, 7] = wall
a[8, 1] = wall
return a
'''def plotMaze(maze2):
m = []
n = []
for i in range(5):
temp = maze2[:, len(maze2)-i-1]
maze2[:, len(maze2)-i-1] = maze2[:, i]
maze2[:, i] = temp
print(temp)
for i in range(len(maze2)):
for j in range(len(maze2)):
if(maze2[i,j] == 100):
m.append(i)
n.append(j)
plt.scatter(m, n)
plt.show()'''
def canPass(x, y, maze): # 预检验是否可通
if(maze[x, y] == 100): # 判断是否通道块
return False
if(maze[x, y] == 10): # 曾经纳入过路径,后来被 pop 了
return False
if(maze[x, y] == 1): # 是否在当前路径上
return False
return True
def recursion(p, a, s, k):
list1 = [3, 2, 1]
if(k!=2):
a[p.x, p.y] = 100
temp = s[-1]
p.x = temp[0]
p.y = temp[1]
direction = list1[k]
p.changeDirection(direction)
k += 1
else:
temp = s.pop()
p.x = temp[0]
p.y = temp[1]
return 222
if(canPass(p.x, p.y, a)):
return 222
else:
return recursion(p, a, s, k)
def main():
end = [8, 8] # 终点
a = initMaze()
print('the init maze is:')
print(a)
print('\n')
x = 1
y = 1
order = 0
a[x, y] = order
direction_x = 0
s = []
p = path(x, y, order, direction_x); # x, y, order, direction
while True:
if(canPass(p.x, p.y, a)): # 如果该位置可通,就到达这个位置
a[p.x, p.y] = 1 # 表示纳入栈
#print(a)
s.append([p.x, p.y])
if(end == s[-1]): # 如果当前位置为终点,就结束
break
p.y = p.y + 1 # 向右边更新位置
else: # 如果该位置不可通,将该位置做上访问过的标记
# 回到上一位置,向下搜索,如果向下搜索成功,抛出处理,会纳入栈
# 如果向下搜索失败,向左搜索,向上搜索,如果搜索失败,就弹出栈顶元素
''' 递归的过程 '''
k = 0
if(recursion(p, a, s, k)==222):
continue
#print(a)
else:
break # 说明没有路径
print('the calculate maze is:')
print(a)
print('\n')
print('the path is:')
print(s)
main()
《严蔚敏数据结构》迷宫求解,python 实现
最新推荐文章于 2022-01-02 23:27:15 发布