Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

recursion - Maze solving with python

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#
####################################

The result that I want to get to is:

####################################
#S#  ##  ######## # #>>>>>v#  ^>v# #
#v#^>v#    >>>v     #^#   >>>>^#>>v#
#>>^#v#####^##v######^# #######  #v#
### #v##^>>^##>>>>>v#^# #     ####v#
#   #>>>^#  #######>>^#   ###    #E#
####################################

How is it possible to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
#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
...

From Lix example. You need to uncomment maze[y][x] = "o", you need that row to prevent the node from being revisited


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...