用python解决迷宫 [英] Maze solving with python
本文介绍了用python解决迷宫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试制作一个迷宫求解器,但它正在运行,除了要用>",<","v","^"标记而不是用"o"标记路径",具体取决于路径的方向.这是解决迷宫的代码部分:
I am trying to make a maze solver, and it is working except that instead of the path being marked by "o" I want it to be marked with ">", "<", "v", "^" depending on the direction of the path. This is the part of the code where it solves the maze:
def solve(self,x,y):
maze = self.maze
#Base case
if y > len(maze) or x > len(maze[y]):
return False
if maze[y][x] == "E":
return True
if maze[y][x] != " ":
return False
#marking
maze[y][x] = "o"
#recursive case
if self.solve(x+1,y) == True : #right
return True
if self.solve(x,y+1) == True : #down
return True
if self.solve(x-1,y) == True : #left
return True
if self.solve(x,y-1) == True : #up
return True
#Backtracking
maze[y][x] = " "
return False
这是一个未解决的迷宫的例子:
This is an example of an unsolved maze:
####################################
#S# ## ######## # # # # #
# # # # # # #
# # ##### ## ###### # ####### # #
### # ## ## # # # #### #
# # # ####### # ### #E#
####################################
这是使用上面的代码的相同迷宫的已解决版本:
And this is the solved version of the same maze using the code above:
####################################
#S# ## ######## # #oooooo# ooo# #
#o#ooo# oooo #o# ooooo#ooo#
#ooo#o#####o##o######o# ####### #o#
### #o##oooo##oooooo#o# # ####o#
# #oooo# #######ooo# ### #E#
####################################
我想要得到的结果是:
####################################
#S# ## ######## # #>>>>>v# ^>v# #
#v#^>v# >>>v #^# >>>>^#>>v#
#>>^#v#####^##v######^# ####### #v#
### #v##^>>^##>>>>>v#^# # ####v#
# #>>>^# #######>>^# ### #E#
####################################
这怎么可能?
推荐答案
#marking
maze[y][x] = "o"
#recursive case
if self.solve(x+1,y) == True : #right
maze[y][x] = ">"
return True
if self.solve(x,y+1) == True : #down
maze[y][x] = "v"
return True
...
以Lix为例.您需要取消注释maze [y] [x] ="o",需要该行以防止再次访问该节点
From Lix example. You need to uncomment maze[y][x] = "o", you need that row to prevent the node from being revisited
这篇关于用python解决迷宫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文