如何走到迷宫的终点?

How to come to the ending point of a maze?

在我的 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

但我需要穿过整个迷宫才能到达终点。这可能是递归调用还是太多了?除了使用递归调用还有其他解决方案吗?

您使用

在递归函数中重新加载文件
array = Maze.read_file('maze-one.txt')

在每个递归步骤中,因此array[x][y] == 4每次都会被重新加载覆盖。 这意味着你的迷宫总是无人问津,你的递归是无限的。

编辑您的评论

我并不是说您应该使用全局变量,但这是一个选项。 在你的情况下,我更喜欢函数参数。

首先,您既不需要静态方法中的 self 参数,也不需要仅包含静态元素的 class 对象,但那是一个不同的主题,这里要解释的内容不多。您可能会自己阅读有关 OOP 的内容。

您可以将迷宫作为函数参数,如下所示:

def search(x, y, array):
    ...

比你从你的主要方法调用它更像:

def main():
    """ Launcher """
    # [1][1] is starting point
    Maze.search(1, 1, Maze.load_file('maze-one.txt'))

search 函数中删除 load_file 行,并以相同的方式更改搜索方法中的 Maze.search 函数调用。

 if ((x < len(array) - 1 and Maze.search(x + 1, y, array))...

第二次编辑

我不太了解您搜索功能的 if 部分。但本能地,如果类似于以下内容,我会将其拆分为单个:

if x < len(array) -1:
    if Maze.search(x + 1, y, array):
        return True

if y > 0:
    if Maze.search(x, y - 1, array):
        return True

if x > 0:
    if Maze.search(x - 1, y, array):
        return True

if y < len(array):
    Maze.search(x, y + 1, array):
        return True

return False