【发布时间】:2014-06-05 19:44:43
【问题描述】:
上下文
我目前正在尝试 Reddit 的 /r/dailyprogrammer challenge。
我们的想法是找到 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?行复制列表?