【问题标题】:Maze Solving Using Stack in Python - is my Algorithm correct?在 Python 中使用堆栈解决迷宫 - 我的算法是否正确?
【发布时间】:2019-02-26 18:10:40
【问题描述】:

我编写了一些 Python 代码来帮助我了解如何使用堆栈而不是递归来解决迷宫问题。

我想出的 SEEMS 可以工作(因为在表示迷宫的二维数组中的目标位置是迷宫的几个版本)。 1 表示墙壁,0 表示空间,2 表示目标,3 表示“已访问”。

但是,我很怀疑,希望有人确认逻辑是否正确,或者如果不正确,我需要做些什么来解决它。

我主要担心的是坐标被放回堆栈,即使它们已经被访问过。

请了解我的情况的鸡和蛋的本质 - 我不完全了解算法的工作原理,所以我编写了一些代码来帮助我理解,但我不确定代码是否正确,部分原因是取决于对算法的理解...

一如既往,非常感谢任何帮助。代码如下:

class Stack:
    def __init__(self):
        self.list = []

    def push(self, item):
        self.list.append(item)

    def pop(self):
        return self.list.pop()

    def top(self):
        return self.list[0]

    def isEmpty(self):
        return not self.list

    def empty(self):
        self.list = []

maze = [[0, 0, 1, 1],
        [0, 1, 0, 1],
        [0, 0, 1, 1],
        [0, 0, 2, 0]]

MAZE_SIZE = len(maze)


def print_maze(maze):
    for row in maze:
        print((row))

def is_valid_pos(tup):
    (col, row) = tup
    if col < 0 or row < 0 or col >= MAZE_SIZE  or row >= MAZE_SIZE :
        return False
    return maze[row][col] == 0 or maze[row][col] == 2


def solve(maze, start):
    s = Stack()
    (col,row) = start
    print('pushing ({},{})'.format(col,row))
    s.push((col,row))

    while not s.isEmpty():
        print('Stack contents: {}'.format(s.list))
        input('Press Enter to continue: ')
        print('Popping stack')
        (col, row) = s.pop()
        print('Current position: ({}, {})'.format(col,row))

        if maze[row][col] == 2:
            print('Goal reached at ({}, {})'.format(col,row))
            return
        if maze[row][col] == 0:
            print('Marking ({}, {})'.format(col,row))
            maze[row][col] = 3
        print_maze(maze)
        print('Pushing coordinates of valid positions in 4 directions onto stack.')
        if is_valid_pos((col+1, row)): s.push((col+1, row)) 
        if is_valid_pos((col, row+1)): s.push((col, row+1))
        if is_valid_pos((row, col-1)): s.push((row, col-1))
        if is_valid_pos((row-1, col)): s.push((row, col))


solve(maze, (0,0))

【问题讨论】:

    标签: python algorithm stack


    【解决方案1】:

    由于在您的坐标系中列总是在行之前,您应该更改:

    if is_valid_pos((row, col-1)): s.push((row, col-1))
    if is_valid_pos((row-1, col)): s.push((row, col))
    

    到:

    if is_valid_pos((col-1, row)): s.push((col-1, row))
    if is_valid_pos((col, row-1)): s.push((col, row-1))
    

    你的代码就可以工作了。

    【讨论】:

    • 好的我已经修改了,所以我希望如果我在足够多的迷宫上运行代码足够多次并遵循结果,我将有一个关于算法如何工作的“啊哈”时刻。您可以添加任何内容来促进这一点吗?看起来还是有点像现在的巫术......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 2015-05-17
    • 1970-01-01
    相关资源
    最近更新 更多