【问题标题】:python maze using recursion使用递归的python迷宫
【发布时间】:2016-05-14 22:41:27
【问题描述】:

我想用递归解决一个迷宫。程序会打开一个像这样的文本文件:

10 20
1 1 
10 20
-----------------------------------------
|     |     | |     | | |       |     | |
|-+ +-+-+ +-+ + +-+ + + +-+-+ +-+-+ + + |
|         |       |     | | | |   | |   |
| + +-+ + + +-+-+-+ + + + + + +-+ + + + |
| | |   |     |     | |     |       | | |
| +-+-+-+-+ +-+ +-+-+-+-+ +-+ + +-+-+ +-|
| | | |       |   | |         | |   |   |
| + + +-+ +-+-+ + + + +-+ +-+ + + + +-+ |
|     |     |   | |     | |   |   | | | |
|-+-+ +-+-+-+-+-+-+-+ +-+ +-+-+ +-+-+ +-|
| |   |   |     |     |     |   | | | | |
| +-+-+ +-+-+ +-+ + +-+-+ +-+ +-+ + + + |
|       |     | | |   |   | | | |       |
|-+ +-+ + + +-+ +-+-+ + +-+ + + +-+ +-+ |
|   | | | |     | | | | | | | |   | | | |
|-+ + +-+ + + + + + +-+ + + + + +-+-+ + |
|       | | | |     |     |             |
| + + +-+ + +-+-+-+ + +-+ + + +-+-+ +-+ |
| | |     | |           | | | |     |   |
-----------------------------------------

文件的第一行是迷宫的大小(10 20),第二行是起点(1 1),第三行是出口(10, 20)。我想用“*”标记正确的路径。这是我的代码的样子:

编辑:我更改了findpath() 函数中的一些代码,现在我没有收到任何错误,但迷宫是空的,路径('*')没有在迷宫上“绘制”。

class maze():    
    def __init__(self, file):

        self.maze_list = []

        data= file.readlines()

        size = data.pop(0).split()  # size of maze

        start = data.pop(0).split() # starting row and column; keeps being 0 because the previous not there anymore
        self.start_i = start[0]  # starting row
        self.start_j = start[1]  # starting column

        exit = data.pop(0).split()   # exit row and column 
        self.end_i = exit[0]
        self.end_j = exit[1]

        for i in data:  
            self.maze_list.append(list(i[:-1])) # removes \n character off of each list of list
        print(self.maze_list) # debug


    def print_maze(self):

        for i in range(len(self.maze_list)):
            for j in range(len(self.maze_list[0])):  
                print(self.maze_list[i][j], end='')                         
            print()

def main():

    filename = input('Please enter a file name to be processed: ') # prompt user for a file


    try:
        file = open(filename, 'r')
    except:                     # if a non-existing file is atempted to open, returns error 
        print("File Does Not Exist")
        return  

    mazeObject = maze(file)
    mazeObject.print_maze() # prints maze

    row = int(mazeObject.start_i)
    col = int(mazeObject.start_j)   

    findpath(row, col, mazeObject)  # finds solution route of maze if any

def findpath(row, col, mazeObject):

    if row == mazeObject.end_i and col == mazeObject.end_j: # returns True if it has found the Exit of the maze
        mazeObject.maze_list[row][col] = ' ' # to delete wrong path
        return True

    elif mazeObject.maze_list[row][col] == "|": # returns False if it finds wall 
        return False

    elif mazeObject.maze_list[row][col] '-': # returns False if it finds a wall 
    return False

    elif mazeObject.maze_list[row][col] '+': # returns False if it finds a wall 
        return False    

    elif mazeObject.maze_list[row][col] '*': # returns False if the path has been visited
        return False

    mazeObject.maze_list[row][col] = '*'   # marks the path followed with an *   

    if ((findpath(row + 1, col, mazeObject)) 
        or (findpath(row, col - 1, mazeObject)) 
        or (findpath(row - 1, col, mazeObject)) 
        or (findpath(row, col + 1, mazeObject))):    # recursion method
        mazeObject.maze_list[row][col] = ' '  # to delete wrong path
        return True
    return False    

所以现在我的问题是,错误在哪里?我的意思是程序只是打印出没有解决方案的迷宫。我想用“*”填充正确的路径。

【问题讨论】:

  • 您的问题到底是什么?查看this question 了解您的错误的含义。这可能会为您提供如何修复它的线索。 :)
  • 这个错误意味着你试图通过数字索引访问迷宫类的对象,例如maze[1],而你想要的是maze.maze_list[1]。对象本身不可下标,因为它没有__getitem__ 方法,不像列表、字符串和元组等类型。
  • @puqeko 好的,我想我明白了,我更新了我的问题。我修复了代码,现在没有出现错误,但路径仍然不会显示在迷宫中
  • 它不会修复您的逻辑,但在您调用findpath 之后打印迷宫 是一个好的开始。此外,您还缺少一些==

标签: python recursion backtracking maze


【解决方案1】:

查看您的代码,我发现了几个错误。您没有正确处理进入和退出行/列对。 (10,20) 对于这个迷宫是正确的,如果您假设每隔一行和每隔一列都是一条网格线。也就是说,如果|- 字符代表无限细的线条,其中偶尔会出现中断,就像传统的迷宫图一样。

您需要乘以/除以二,并处理不可避免的栅栏错误,以便将文件参数正确转换为数组行/列值。

接下来,你的findpath 函数被混淆了:

首先,它应该是类的方法。它访问内部数据,并包含有关类详细信息的“内部知识”。让它成为一种方法!

其次,您的退出条件将当前字符替换为空格“删除错误路径”。但是,如果您找到了出口,则路径根据定义是正确的。不要那样做!

第三,你有一堆用于各种字符类型的 if 语句。这很好,但请使用

将它们替换为单个 if 语句
if self.maze_list[row][col] in '|-+*':
    return False

第四,您要等到检查后才用“*”标记当前单元格。但是,当您到达出口位置时,您应该在宣布胜利之前标记单元格。我想,把退出测试往下移。

这应该可以很好地清理东西。

第五,也是最后,你的递归测试是倒退的。您的代码在到达退出位置时返回 True。当您的代码撞到墙壁或试图越过自己的路径时,它会返回 False。因此,如果代码走死胡同,就会走到尽头,返回false,展开递归几次,一直返回false,直到回来。

因此,如果您看到True 返回,您就知道代码找到了该路径的出口。您想立即返回 true 并执行 其他任何操作。当然不要抹去路径——它通向出口!

另一方面,如果所有可能的方向都没有返回真,那么你已经找到了一个死胡同——出口不在这个方向。你应该擦掉你的路径,返回False,希望能在更高的层次上找到出口。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    相关资源
    最近更新 更多