迷宫递归求解python

问题描述 投票:0回答:0

我需要使用递归算法解决迷宫问题。但是,如果有空路径,每当我尝试解决迷宫问题时都会出现索引错误。我认为移动不会停止,直到它超出边界。有什么想法吗?我将发布解决迷宫的部分代码

    def find_exits(self, start_row, start_col) :#depth) -> bool:
        """Find and save all exits into `self._exits` using recursion, save
        the maximum recursion depth into 'self._max_recursion_depth' and mark the maze.

        An exit is an accessible from S empty cell on the outer rims of the maze.

        Args:
            start_row (int): row to start from. 0 represents the topmost cell.
            start_col (int): column to start from; 0 represents the leftmost cell.
            depth (int): Depth of current iteration.

        Raises:
            ValueError: If the starting position is out of range or not walkable path.
        """


        # base case
        if start_row < 0 or start_row >= self._row_range or start_col < 0 or start_col >= self._col_range :
           raise ValueError("Starting position is out of range ")

        if   self._maze[start_row][start_col] == OBSTACLE:
           raise ValueError("Starting position is not a valid path.")
        else:
            self._maze[start_row][start_col] = START


        if self._maze[start_row][start_col] == EXIT and self._maze[start_row][start_col] != OBSTACLE :
                self._exits.append((start_row, start_col))
                return True

        self._maze[start_row][start_col] = VISITED
        for r, c in [
           (0, 1) ,#East
           (1, 1) , #SOUTHEAST
           (1, 0) ,#SOUTH
           (1,-1),#southwest
           (0,-1),#west
           (-1,-1),#northwest
           (-1,0) ,#north
           (-1,1) ,#northeast
        ]:
                # set new position to neighbor
                new_row, new_col = start_row + r, start_col  + c

             
                if  self._maze[new_row][new_col] == PATH:
                    self._maze[new_row][new_col] = VISITED
                    self.find_exits(new_row, new_col)

我总是得到这个错误:[上一行重复了 27 次以上]

  File "C:\Users\alime\OneDrive\Desktop\JKU\A and Ds Ass\ass 3\my_maze.py", line 83, in find_exits
    self._maze[new_row][new_col] == PATH:
    ~~~~~~~~~~~~~~~~~~~^^^^^^^^^
IndexError: list index out of range
python recursion maze
© www.soinside.com 2019 - 2024. All rights reserved.