I am trying to write a code that solves a basic maze made up of a list of lists with '#' symbolizing walls, '.' are free spaces, S is the start and E is the end. My algorithm consists of first checking to see if the space to the right is free, if not it then checks the space up, then down, and finally to the left. I also realize that this creates a problem if there is a dead end but I'll worry about that later. So far I have code that prints the list and finds the index value of the start point which is (2,0). Basically what I am trying to do is take that starting value as the argument for my def solve function and then iterate over my algorithm while marking visited positions as 'x'... if that makes any sense. When I run the code I keep getting
if maze[r+1][c] == '.':
NameError: name 'r' is not defined
Also I can't seem to print my maze correctly on this website so
here is my maze.
def main():
print_maze()
start()
solve(start())
print_maze()
def print_maze():
for r in range(0,len(maze)):
for c in range(0,len(maze)):
print(maze[r][c], end='')
print('')
def start():
find_value = 'S'
for r in range(0,len(maze)):
for c in range (0,len(maze)):
if find_value in maze[r][c]:
return(r,c)
break
def solve(position):
if maze[r+1][c] == '.':
maze[r][c] = 'x'
return (r,c)
elif maze[r][c+1] == '.':
maze[r][c] = 'x'
return (r,c)
elif maze[r][c-1] == '.':
maze[r][c] = 'x'
return (r,c)
elif maze[r-1][c] == '.':
maze[r][c] = 'x'
return (r,c)
else:
print('Route Error')
main()
解决方案
Try to change the def slove format eg; == "X"
= "x²"