如何使用python中的函数解决基本的迷宫? [英] How to solve a basic maze using functions in python?
问题描述
我正在尝试编写代码来解决基本迷宫,该迷宫由带有#"的符号表示墙壁."的列表组成.是自由空间,S是开始,E是结束.我的算法包括首先检查右边的空间是否空闲,如果不是,则检查该空间的大小,然后向下,最后检查左边.我还意识到,如果出现死胡同,这会带来问题,但我稍后会担心.到目前为止,我有代码可以打印列表并找到起点的索引值为(2,0).基本上,我想做的就是以该起始值作为defsolve函数的参数,然后遍历我的算法,同时将访问的位置标记为"x"……如果有任何意义.当我运行代码时,我不断得到
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
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()
推荐答案
尝试更改def slove格式,例如; =="X" =x²"
Try to change the def slove format eg; == "X" = "x²"
这篇关于如何使用python中的函数解决基本的迷宫?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!