title: solving maze in python
body: <p>I found this code to solve a maze like this:</p>
  
  <pre><code>+-+-+-+-+-+-+-+-+-+-+
  | |         |   |   |
  S +-+-+-+-+ + +-+ + +
  |         | |     | |
  +-+-+-+ +-+ +-+-+-+ +
  |     | |   |       |
  + + + + + +-+ +-+-+-+
  | | | | |       |   |
  + + +-+ +-+-+ + + + +
  | |   | |   | |   | |
  + +-+ + + + + +-+-+-+
  | |   |   | |       |
  + + +-+-+-+ + +-+-+ +
  | |         | |     |
  + +-+-+ +-+-+ +-+-+-+
  | |   |     |   |   |
  + + + +-+-+-+-+ + +-+
  | | | | |       |   |
  + + + + + + +-+-+-+ +
  |   |     |         E
  +-+-+-+-+-+-+-+-+-+-+
  </code></pre>
  
  <p>this is the code:</p>
  
  <pre><code>def read_maze(fname):
      mz = []
      with open(fname, 'U') as f:
          for r in f:
              mz.append(list(r.replace('\n', '')))
      return mz
  
  
  
  PATH, START, EXIT, VISITED, SOLUTION = " SE.o"
  
  
  class Maze():
      def __init__(self,maze):
          self.maze = maze
          self.start_y = [row.count(START) for row in self.maze].index(1)
          self.start_x = self.maze[self.start_y].index(START)
      def __repr__(self):
          return  "\n".join("".join(row)for row in self.maze)
      def solve(self, x=None, y=None):
          if x==None:
              x, y = self.start_x,self.start_y
          if self.maze[y][x] in (PATH,START):
              self.maze[y][x] = VISITED
              if self.solve(x+1,y) or self.solve(x-1,y) or self.solve(x,y+1) or self.solve(x,y-1):
                  self.maze[y][x]=SOLUTION
                  return True
          elif self.maze[y][x] == EXIT:
              return True
          return False
  
  maze = read_maze("maze.txt")
  
  
  mz = Maze(maze)
  print (mz)
  print ("-----------------------------")
  if mz.solve():
      print(mz)
  </code></pre>
  
  <p>can anyone help me to understand the recursive function <code>solve()</code>?</p>
  
  <p>First of all, the function check if the current position is in PATH or START, it will be obviously in START for the first time, that in our case is (x=0;y=2). So the code mark it as VISITED.</p>
  
  <p>What I dont completely understand is what the program do next? There is an if condition and the first option to check is <code>self.solve(x+1,y)</code> - in this case we are going to right, that is a free position and it is in PATH (so we mark it as VISITED), but (x+1+1,y) is not, so we pass to the second value of our <code>or</code> (that is <code>(x-1,y)</code> so we obtain again <code>(x+1+(1-1),y) = (x+1,y)</code>, now we pass to the third <code>(x,y+1)</code> so we go down etc.</p>
  
  <p>Is it correct? i'm lost a bit.</p>