【发布时间】:2019-06-04 17:37:03
【问题描述】:
在我的 read_file 方法代码中,我正在读取一个文件并返回一个包含迷宫线的二维数组。 例如。 [[1 0 0 0 0 1 0 0], [0 0 0 1 0 0 1 0 0]]
2 是迷宫的起点,3 是迷宫的终点。
import numpy as np
class Maze:
@staticmethod
def read_file(file):
""" function that reads the file and returns the content of the file in an array """
# dict for replacements
replacements = {'*': 0, ' ': 1, 'A': 2, 'B': 3}
# open and read file
file = open(file, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
# create array
maze_array = np.zeros((rows, cols), dtype=int)
# add lines to array
for index, line in enumerate(lines):
for i in range(0, len(line) - 1):
# replace line content with the ones from the dictionary and add it to the array
maze_array[index][i] = replacements.get(line[i], line[i])
return maze_array
现在我想通过迷宫得到终点,从起点开始。为此,我编写了一个名为 search 的方法。在这种方法中,我检查了迷宫的单元格。 当一个单元格等于 3 时,我找到了迷宫的尽头。等于 0 是一堵墙,等于 1 是我可以穿过的空单元格。通过单元格后,我将它们设置为 4 以将其标记为已访问。然后是下面的递归调用。
@staticmethod
def search(x, y, array):
"""
0: wall
1: empty
2: starting point
3: ending point
4: visited cell
"""
if array[x][y] == 3:
print('end at %d,%d' % (x, y))
return True
elif array[x][y] == 0:
print('wall at %d,%d' % (x, y))
return False
elif array[x][y] == 4:
print('visited at %d,%d' % (x, y))
return False
print('visiting %d,%d' % (x, y))
array[x][y] == 4
if ((x < len(array) - 1 and Maze.search(x + 1, y, array))
or (y > 0 and Maze.search(x, y - 1, array))
or (x > 0 and Maze.search(x - 1, y, array))
or (y < len(array) - 1 and Maze.search(x, y + 1, array))):
return True
return False
def main():
""" Launcher """
# [1][1] is starting point
array = Maze.read_file("maze-one.txt")
Maze.search(1, 1, array)
if __name__ == "__main__":
main()
它不起作用。感谢@Florian H,我已经更改了我的代码,但我仍然收到以下错误:
RecursionError: maximum recursion depth exceeded while calling a Python object
但我需要走遍整个迷宫才能到达终点。这可以通过递归调用实现还是太多了?除了使用递归调用还有其他解决方案吗?
【问题讨论】:
-
不是在每个单元格递归调用,而是在交叉路口递归调用。这将改善堆栈要求,但可能还不够。我建议使用数组或列表而不是堆栈来存储您想要返回的交点。