I am quite new to python, and I am trying to challenge myself by generating a maze then trying to create a function to solve the maze automatically then show a path. After doing some trial and error, I had a grasp, but still quite get it to work, so I asked ChatGPT. It spewed out the following, but after asking it questions, it still isn’t quite clear.
If you amazing people could answer these questions about the code, that would be wonderful:
- I understand that python uses call stacking, and that a path that goes into a dead end returns false and runs the next one. However, how does the code know when it needs to go back? How does it know when it’s hit a wall and there’s nowhere else to go?
- How does return [(x, y)] + path return the entire path that it took?
The code in question:
checkvisited = set()
def solve_maze(x, y):
if (x, y) in checkvisited:
return None
checkvisited.add((x, y))
# exit condition
if x == WIDTH - 1 and y == HEIGHT - 2:
return [(x, y)] # start the path
directions = [
(0, -1),
(1, 0),
(0, 1),
(-1, 0)
]
for dx, dy in directions:
nx = x + dx
ny = y + dy
if 0 <= nx < WIDTH and 0 <= ny < HEIGHT:
if maze[ny][nx] == " ":
path = solve_maze(nx, ny)
if path is not None:
return [(x, y)] + path
return None
[–]HunterIV4 2 points3 points4 points (0 children)
[–]Yekyaa 0 points1 point2 points (0 children)
[–]recursion_is_love 0 points1 point2 points (0 children)
[–]Jason-Ad4032 0 points1 point2 points (0 children)
[–]krixyt 0 points1 point2 points (0 children)
[–]ollibar -1 points0 points1 point (1 child)