【发布时间】: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))
【问题讨论】: