用连续字母标记迷宫解决方案路径

2024-05-23 15:22:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做一个迷宫解算器,虽然我所有的东西都能正常工作,但我一部分都不能工作。我需要用字母表的升序字母(a-z)而不是单个字符来标记“解决方案路径”。你知道吗

我不能让它继续在字母表字符列表上迭代,我所能达到的最好效果就是在字母“a”处停下来,把所有字母都改成那个字母。你知道吗

迷宫:

###_###
#_____#
#_##_##
#_##__#
#_#####

“解决的迷宫”:

###a###
#aaa__#
#a##_##
#a##__#
#a#####

代码:

PATH = "_"
START = "_"
VISITED = "."
SOLUTION = "o"

class Maze:
    def __init__(self, ascii_maze):
        # splits maze string into separate values on each new line
        # uses list comp. to create 'matrix' out of maze
        self.maze = [list(row) for row in ascii_maze.splitlines()]
        # finds index first '_' character which denotes the beginning
        self.start_y = [row.count(START) for row in self.maze].index(1)
        # finds position where '_' is located within the 'y' line which returns the index position
        self.start_x = self.maze[self.start_y].index(START)

    # returns string representation of maze object, joining maze elements passed in as parameters
    # used to print maze with 'cells' and be user friendly
    def __repr__(self):
        return "\n".join("".join(row) for row in self.maze)

    def solve_maze(self, x=None, y=None):
        # assigns starting (x,y) position
        if x is None:
            x, y = self.start_x, self.start_y
        # checks if the coordinate is in the path/start
        if self.maze[y][x] in (PATH, START):
            # marks spot as 'visited' for recursion check
            self.maze[y][x] = VISITED
            # uses recursion to check paths by checking each direction and making a decision off that
            try:
                if (self.solve_maze(x+1, y) or
                        self.solve_maze(x-1, y) or
                        self.solve_maze(x, y+1) or
                        self.solve_maze(x, y-1)):
                    self.maze[y][x] = SOLUTION
                    return True
            # this exception is what occurs when the program tries to leave the maze (aka it found the exit)
            # also marks it
            except IndexError:
                self.maze[y][x] = SOLUTION
                return True
        return False


if __name__ == "__main__":
    import sys
    alphabet_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k','l', 'm', 'n',
                     'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    # for checking mazes through terminal
    if len(sys.argv) > 1:
        maze = Maze(open(sys.argv[1]).read())
    # if none available, defaults to 'maze' text file
    else:
        maze = Maze(open('maze').read())
    # prints string representation of maze to replace "visited" areas (. char used for testing) with original "_"
    if maze.solve_maze():
        # converting to string allows for easy replacement of things
        maze = str(maze)
        maze = maze.replace(".", "_")
        for char in maze:
            if char == "o":
                for item in alphabet_list:
                    maze = maze.replace(char, item)

    print(maze)

Tags: ofthetoinselfforstringif
1条回答
网友
1楼 · 发布于 2024-05-23 15:22:26

由于需要将解决方案字符设置为其已解决的字符(仅通过不知道的字符串操作很难在事后重新创建此字符,这实际上是在重新导航整个解决方案路径):

我们将使用helper函数返回字母表中的下一个字符,并在“z”处重置:

SOLUTION = ord('a') - 1
def getSolutionChar():
    global SOLUTION
    if SOLUTION >= ord('z'):
        SOLUTION = ord('a')
    else:
        SOLUTION += 1
    return chr(SOLUTION)

替换try块:

        try:
            if (self.solve_maze(x+1, y) or
                self.solve_maze(x-1, y) or
                self.solve_maze(x, y+1) or
                self.solve_maze(x, y-1)):
                self.maze[y][x] = getSolutionChar()
                return True
        except IndexError:
            self.maze[y][x] = getSolutionChar()
            return True

不要忘记删除以下内容,因为它不再需要:

alphabet_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k','l', 'm', 'n',
                 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

    for char in maze:
        if char == "o":
            for item in alphabet_list:
                maze = maze.replace(char, item)

相关问题 更多 >