Python练习(3)——迷宫寻路算法
用数组创建出一个迷宫,0为可以通过的路径,1为墙壁。
#定义数组,创建一个迷宫
l = [[0, 0, 1, 1, 1],
[1, 0, 1, 1, 1],
[0, 0, 1, 0, 0],
[0, 1, 1, 0, 1],
[0, 0, 0, 0, 1]]
for i in l:
print(i)
用两个数组记录开始的位置和已走过的位置
stack = [[0, 0]] #开始位置
history = [[0, 0]] #已走过的位置
定义上、下、左、右四个函数实现对当前位置四周能走路径的判断。
def up(location):
if location[1] == 0:
return False
else:
new_location = [location[0], location[1] - 1]
if new_location in history:
return False
elif l[new_location[0]][new_location[1]] == 1:
return False
else:
stack.append(new_location)
history.append(new_location)
return True
def down(location):
if location[1] == 5:
return False
else:
new_location = [location[0], location[1] + 1]
if new_location in history:
return False
elif l[new_location[0]][new_location[1]] == 1:
return False
else:
stack.append(new_location)
history.append(new_location)
return True
def left(location):
if location[0] == 0:
return False
else:
new_location = [location[0] - 1, location[1]]
if new_location in history:
return False
elif l[new_location[0]][new_location[1]] == 1:
return False
else:
stack.append(new_location)
history.append(new_location)
return True
def right(location):
if location[0] == 5:
return False
else:
new_location = [location[0] + 1, location[1]]
if new_location in history:
return False
elif l[new_location[0]][new_location[1]] == 1:
return False
else:
stack.append(new_location)
history.append(new_location)
return True
while stack[-1] != [2, 4]:
location = stack[-1] #将当前位置传入参数location中
if up(location):
location = stack[-1]
continue
if down(location):
location = stack[-1]
continue
if left(location):
location = stack[-1]
continue
if right(location):
location = stack[-1]
continue
stack.pop()
print('迷宫路径为:')
print(stack)