stack一般用来存储已有的状态,对于解决迷宫问题最是合适.
迷宫问题没有什么好的解决办法,只能采用蛮力穷举的办法,要点是已经走过的路径(包括可行路线和不可行路线)要进行标记,这样可以避免原地死循环
# 用list实现一个stack class Stack(object): def __init__(self): self.item = list() # 入栈 def push(self, node): self.item.append(node) # 删除并返回栈顶一个元素 def pop(self): return self.item.pop() # 返回栈顶一个元素 def peek(self): return self.item[-1] def __str__(self): return str(self.item) class Maze(object): MAZE_WALL = "*" PATH_TOKEN = "x" TRIED_TOKEN = "o" def __init__(self): self.maze_cells = [['*', '*', '*', '*', '*'], ['*', None, '*', None, '*'], ['*', None, None, None, '*'], ['*', None, '*', None, None], ['*', None, '*', '*', '*']] self.start = (4, 1) self.end = (3, 4) self.numRows, self.numCols = (5, 5) self.path = None # 搜索可行路线 def find_path(self): self.path = Stack() # 起始点肯定是必经之路,入栈,标记为路径 row, col = self.start self._mark_path(row, col) while not self._exit_found(row, col): # 左1=col-1 if self._valid_move(row, col - 1): self._mark_path(row, col - 1) col = col - 1 # 上1=row-1 elif self._valid_move(row - 1, col): self._mark_path(row - 1, col) row = row - 1 # 右1=col+1 elif self._valid_move(row, col + 1): self._mark_path(row, col + 1) col = col + 1 # 下1=row+1 elif self._valid_move(row + 1, col): self._mark_path(row + 1, col) row = row + 1 else: self._mark_tried(row, col) row, col = self.path.peek() return self.path # 判断是否是可行进路线 def _valid_move(self, row, col): return 0 <= row < self.numRows and 0 <= col < self.numCols and self.maze_cells[row][col] is None # 判断是否找到出口 def _exit_found(self, row, col): return (row, col) == self.end # 标记为已尝试但不可行path def _mark_tried(self, row, col): self.maze_cells[row][col] = self.TRIED_TOKEN self.path.pop() # 标记为可行路线 def _mark_path(self, row, col): self.maze_cells[row][col] = self.PATH_TOKEN self.path.push((row, col)) if __name__ == '__main__': m = Maze() path = m.find_path() print(path)