basic programming python: Python-based recursive algorithm implementation issues Maze

This paper describes examples of problems Maze Python recursive algorithm implemented. Share to you for your reference, as follows:

What is recursion?

Simple to understand is the function that calls itself the process is called recursion.

When to use recursion?

If a problem can be expressed as iteration smaller scale, you can use a recursive algorithm.
Maze: a two-dimensional array consisting of 0 or 1, 1 is assumed to move to the point, it is 0 can not move to the point, how to proceed from a point intermediate the array value is 1, only upward and downward each four directions moving a unit, when moving to the edge of a two-dimensional array, the solution of the problem can be obtained, similar problems can be referred to as a maze.

You can use a nested list represents a two-dimensional array in python. [3] [3] Assuming maze starting a 6 * 6, the question from the array coordinates, can not judge the success of the maze.

maze=[[1,0,0,1,0,1],
   [1,1,1,0,1,0],
   [0,0,1,0,1,0],
   [0,1,1,1,0,0],
   [0,0,0,1,0,0],
   [1,0,0,0,0,0]]

For this maze, we can use the idea of ​​recursive good solution. For a dot array, four directions of the point can be easily represented, whenever a movable point of time to move the whole issue has become a problem as the initial state and by adding or subtracting the horizontal and vertical coordinates, the search continues four directions can be moved to find a point, move to the edge of the array known.

So we can code:

# 判断坐标的有效性,如果超出数组边界或是不满足值为1的条件,说明该点无效返回False,否则返回True。
def valid(maze,x,y):
  if (x>=0 and x<len(maze) and y>=0 and y<len(maze[0]) and maze[x][y]==1):
    return True
  else:
    return False
# 移步函数实现
def walk(maze,x,y):
  # 如果位置是迷宫的出口,说明成功走出迷宫
  if(x==0 and y==0):
    print("successful!")
    return True
  # 递归主体实现
  if valid(maze,x,y):
    # print(x,y)
    maze[x][y]=2 # 做标记,防止折回
    # 针对四个方向依次试探,如果失败,撤销一步
    if not walk(maze,x-1,y):
      maze[x][y]=1
    elif not walk(maze,x,y-1):
      maze[x][y]=1
    elif not walk(maze,x+1,y):
      maze[x][y]=1
    elif not walk(maze,x,y+1):
      maze[x][y]=1
    else:
      return False # 无路可走说明,没有解 
  return True
walk(maze,3,3)

Recursion is a good thing ah!
Content on more than how many, and finally to recommend a good reputation in the number of public institutions [programmers], there are a lot of old-timers learning skills, learning experience, interview skills, workplace experience and other share, the more we carefully prepared the zero-based introductory information on actual project data every day to explain the timing of Python programmers technology, to share some of the ways to learn and need to pay attention to small details, to remember the attention I
Here Insert Picture Description

Released six original articles · won praise 0 · Views 4

Guess you like

Origin blog.csdn.net/chengxun02/article/details/104976841