【发布时间】:2020-07-17 19:21:03
【问题描述】:
我的代码成功通过了迷宫中所有可能的路径...但它总是返回True,即使只有在满足某些条件时才会更新 true(已经到达边缘迷宫)。 看来我对范围有误解。这是我第一次使用 global 关键字。
这是一些示例输入/输出。上面是迷宫,两个数字是迷宫中当前位置的(x,y)坐标。 'k' 是起始位置,'#' 是墙。
# # ## #
# #k# #
# # # ##
# # # #
# ##
########
3 2
3 3
3 4
3 5
4 5
5 5
5 4
6 4
5 3
5 2
6 2
6 1
2 5
1 5
1 4
1 3
1 2
1 1
3 1
True
found = False
def find_start(maze):
start = None
for i in range(len(maze)):
print(maze[i])
for j in range(len(maze[i])):
if maze[i][j] == 'k':
if start == None:
start = (i, j)
else:
raise "There should be no multiple Kates"
if not start:
raise "There should be one Kate"
return start
def has_exit(maze):
visited = [[False for _ in range(len(maze[i]))] for i in range(len(maze))]
y, x = find_start(maze)
def backtrack(maze, x, y):
visited[y][x] = True
print(x, y)
if x == 0 or x == (len(maze[y]) - 1) or y == 0 or y == (len(maze) - 1) or x > len(maze[y+1]) - 1 or x > len(maze[y-1]) - 1: # This last condition is the hard one.
print('Found edge')
global found
found = True
return
if maze[y][x+1] == ' ' and not visited[y][x+1]:
backtrack(maze, x+1, y)
if maze[y][x-1] == ' ' and not visited[y][x-1]:
backtrack(maze, x-1, y)
if maze[y+1][x] == ' ' and not visited[y+1][x]:
backtrack(maze, x, y+1)
if maze[y-1][x] == ' ' and not visited[y-1][x]:
backtrack(maze, x, y-1)
backtrack(maze, x, y)
if found:
print(found)
return True
else:
print(found)
return False
【问题讨论】:
-
你用什么资源来学习 Python?
raise "..."在 ages 之前已被弃用,在 Python 3 甚至 Python 2.7 中都是不合法的。 -
另外,不要使用全局变量。有
backtrack返回一个值。
标签: python scope global recursive-backtracking