我目前正在尝试Reddit的/ r / dailyprogrammer挑战。
这个想法是找到ASCII迷宫的解决方案。不幸的是,递归的工作方式与我预期的不同。程序检查是否有空间可移动到当前空间的右侧,左侧,下方或上方。如果存在,则将空间移至该位置,并使用新的坐标再次输入该功能。这一直持续到找到结尾为止。
找到结尾时,程序退出。如果发现死角,则递归将返回到上一点,并检查是否有其他方向,这种情况将一直持续到结束为止。
我的程序运行良好,但是即使备份了递归,迷宫也会画出我的线条(用“ *****”表示)。我不知道该怎么解释,所以我将使用图像进行更好的描述。
每种新颜色都代表一条新路径。但是,我希望仅显示当前的递归路径。例如,在这种情况下,我希望仅显示黄色路径。有人可以帮助我理解为什么仍然保留所有路径吗?
import time
import sys
import os
maze = """\
###############
#S # #
### ### ### # #
# # # # #
# ##### ##### #
# # # #
# ### # ### ###
# # # # # #
# # ### # ### #
# # # # # # #
### # # # # # #
# # # # # #
# ####### # # #
# #E#
###############"""
def displayMaze(maze):
os.system("cls")
display = ""
for x in maze:
for y in x:
display = display + y
display = display + "\n"
print(display)
def findStart(maze):
#Get the maze start co-ords.
for x in range(0,len(maze[0])):
for y in range(0,len(maze)):
if maze[x][y] == "S":
return x,y
def findPath(x,y,maze):
#Look right, left, up and down, If path then move.
time.sleep(0)
if maze[y][x+1] == " ":
newMaze = maze
newMaze[y][x+1] = "*"
displayMaze(newMaze)
findPath(x+1,y,newMaze)
elif maze[y][x+1] == "E":
sys.exit("Done")
if maze[y][x-1] == " ":
newMaze = maze
newMaze[y][x-1] = "*"
displayMaze(newMaze)
findPath(x-1,y,newMaze)
elif maze[y][x-1] == "E":
sys.exit("Done")
if maze[y+1][x] == " ":
newMaze = maze
newMaze[y+1][x] = "*"
displayMaze(newMaze)
findPath(x,y+1,newMaze)
elif maze[y+1][x] == "E":
sys.exit("Done")
if maze[y-1][x] == " ":
newMaze = maze
newMaze[y-1][x] = "*"
displayMaze(newMaze)
findPath(x,y-1,newMaze)
elif maze[y-1][x] == "E":
sys.exit("Done")
if __name__ == "__main__":
maze = maze.split("\n")
newMaze = []
for line in maze:
newMaze.append(list(line))
x,y = findStart(newMaze)
findPath(x,y,newMaze)
newMaze = maze
不复制列表,它只是创建一个指向同一对象的名称。要复制,您应该import copy
在程序的顶部,然后执行newMaze = copy.deepcopy(maze)
。(您需要深层复制,因为它maze
是一个列表列表,因此不仅需要复制外部列表,还需要复制其中的所有列表。)
在Python中,分配给纯名称(如blah = ...
)绝不会复制任何内容。如果要复制,则必须显式复制一个。这样做的方式取决于您要复制的内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句