Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Implement a Maze Solving Algorithm

Python Implement a Maze Solving Algorithm

Document Object Reference Manual Python3 Examples

We will use the Depth-First Search (DFS) algorithm to solve a simple maze problem. The maze is represented by a 2D array, where 0 represents a passable path,1 represents a wall,2 represents the start,3 represents the end. We will start from the start and try to find a path to the end.

Example

def

solve_maze

(

maze

,

start

,

end

)

:

    rows

,

cols

=

len

(

maze

)

,

len

(

maze

[

0

]

)

    visited

=

[

[

False

for

_

in

range

(

cols

)

]

for

_

in

range

(

rows

)

]

    path

=

[

]

   

def

dfs

(

x

,

y

)

:

       

if

x

=

rows

or

y

=

cols

or

maze

[

x

]

[

y

]

==

1

or

visited

[

x

]

[

y

]

:

           

return

False

        visited

[

x

]

[

y

]

=

True

        path.

append

(

(

x

,

y

)

)

       

if

(

x

,

y

)

==

end:

           

return

True

       

for

dx

,

dy

in

[

(

1

,

0

)

,

(

1

,

0

)

,

(

0

,

1

)

,

(

0

,

1

)

]

:

           

if

dfs

(

x + dx

,

y + dy

)

:

               

return

True

        path.

pop

(

)

       

return

False

   

if

dfs

(

start

[

0

]

,

start

[

1

]

)

:

       

return

path

   

else

:

       

return

None

Example maze

maze

=

[

   

[

2

,

0

,

1

,

0

,

0

]

,

   

[

1

,

0

,

1

,

0

,

1

]

,

   

[

0

,

0

,

0

,

0

,

1

]

,

   

[

1

,

1

,

0

,

1

,

1

]

,

   

[

0

,

0

,

0

,

0

,

3

]

]

start

=

(

0

,

0

)

end

=

(

4

,

4

)

result

=

solve_maze

(

maze

,

start

,

end

)

print

(

result

)

Code analysis:

  1. solve_maze The function accepts the maze, start, and end as parameters.
  2. visited is a 2D array used to record which positions have been visited, to avoid revisiting.
  3. path is a list used to store the path from start to end.
  4. dfs is a recursive function for depth-first search. It first checks whether the current position is out of bounds, is a wall, or has already been visited. If any of these conditions hold, it returns False。
  5. If the current position is the end, return True, indicating a path has been found.
  6. For the four directions (up, down, left, right) of the current position, recursively call dfs function. If a path is found, return True。
  7. If all directions have been tried but no path was found, remove the current position from path and return False。
  8. Finally, if dfs the function returns True, return path; otherwise, returns None。

Output result:

[(0, 0), (0, 1), (1, 1), (2, 1), (2, 2), (2, 3), (2, 4), (3, 4), (4, 4)]

this result indicates the path from start (0, 0) to end (4, 4) .

Document Object Reference Manual Python3 Examples