Python Implement a Maze Solving Algorithm
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
)
(
result
)
Code analysis:
solve_mazeThe function accepts the maze, start, and end as parameters.visitedis a 2D array used to record which positions have been visited, to avoid revisiting.pathis a list used to store the path from start to end.dfsis 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 returnsFalse。- If the current position is the end, return
True, indicating a path has been found. - For the four directions (up, down, left, right) of the current position, recursively call
dfsfunction. If a path is found, returnTrue。 - If all directions have been tried but no path was found, remove the current position from
pathand returnFalse。 - Finally, if
dfsthe function returnsTrue, returnpath; otherwise, returnsNone。
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) .
Python3 Examples