Here is a code I developed some time ago. I wonder if there is anything I can do to improve it. It works for non-loopy mazes which was already my goal.
In the maze defined, True
are the open ways and False
are the walls.
The main subjects that I gladly accept suggestions can be listed like this:
- Is the solution pythonic, if not what can be done to improve?
- Because of the recursion, after I reach the ending point, I cannot directly return the true_path because the dead ends encountered by the player makes the function return None. So I have to save it in another variable and let the recursion end after that. It is not directly an issue but I am eager to hear suggestions about it.(That is the reason i didn't return the recursions done in the function. They are just called.)
- Is a
while
loop a better solution to this kind of problem? - Even if the solution is pythonic, are there any better ways to implement this path finding algorithm.
def possible_paths(maze, coor):
# This function checks the 4 available routes around the current point.
paths = [
(coor[0]- 1, coor[1]),
(coor[0],coor[1]-1),
(coor[0], coor[1] + 1),
(coor[0] + 1, coor[1])
]
possible_paths = []
for path in paths:
if path[0] >= 0 and path[1] >= 0 and path[0] < len(maze[0]) \
and path[1] < len(maze):
if maze[path[1]][path[0]]:
possible_paths.append(path)
return possible_paths
answer = []
def solve(maze, pos, exit, true_path = []):
global answer
paths = [path for path in possible_paths(maze, pos) if path not in true_path]
if pos == exit:
answer = true_path
elif len(paths) == 1:
pos = paths[0]
true_path.append(pos)
solve(maze, pos, exit, true_path)
else:
for path in paths:
temp_path = true_path[:] + [path]
solve(maze, path, exit, temp_path)
maze = [[True, False, True, False],
[True, False, True, False],
[True, True , True, False],
[True, False, False, False],
[True, True, True, True],
[True, False, False, False]]
solve(maze, (0,0), (2,0), [(0,0)])
print answer
# Gives [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), (2, 1), (2, 0)]
Note: Please notice that (2,0) is a coordinate, so it is actually equivalent to maze[0][2]
.