栈(stack)又名堆栈,它是一种运算受限的线性表
栈只能在一端进行插入和删除操做,它按照先进后出(FILO)的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶
栈也能够当作是 FILO 的队列 <- 点击查看html
示例:node
class Stack(object): def __init__(self): self.stack = [] def push(self, data): """ 进栈函数 """ self.stack.append(data) def pop(self): """ 出栈函数, """ return self.stack.pop() def gettop(self): """ 取栈顶 """ return self.stack[-1]
class Stack(object): def __init__(self): self.stack = [] def push(self, data): """ 进栈函数 """ self.stack.append(data) def pop(self): """ 出栈函数, """ return self.stack.pop() def gettop(self): """ 取栈顶 """ return self.stack[-1] def main(string): stack = Stack() check_dict = { ')': '(', ']': '[', '}': '{' } for char in string: if char in {'(', '[', '{'}: stack.push(char) elif char in {')', ']', '}'} and len(stack.stack) > 0: if stack.gettop() == check_dict[char]: stack.pop() else: return False if len(stack.stack) == 0: return True else: return False print(main('{[()]}()[{()}]'))
思路:从起点开始按照顺序寻找路径,经过栈记录已经走过的路径。若是最后发现不通就返回上一步,换个方向继续寻找
深度优先python
def find_path(x1, y1, x2, y2): """ 运用栈寻找迷宫路径 迷宫中 0 表示能够经过,1 表示没法经过,-1 表示已经走过的路 左上角坐标为 (0, 0),横轴为 y 轴,纵轴为 x 轴 迷宫四周必须用 1 围起来 :param int x1:起点 x 轴坐标 :param int y1:起点 y 轴坐标 :param int x2:终点 x 轴坐标 :param int y2:终点 y 轴坐标 :return: 是否找到出口 :rtype: bool """ paths = [lambda x, y: (x - 1, y), # 上 lambda x, y: (x, y + 1), # 右 lambda x, y: (x + 1, y), # 下 lambda x, y: (x, y - 1)] # 左 # 从起点进入迷宫 stack = list() maze[x1][y1] = -1 stack.append((x1, y1)) while len(stack) > 0: cur_node = stack[-1] # 当前位置 if cur_node[0] == x2 and cur_node[1] == y2: # 到达终点 for p in stack: print(p) return True for path in paths: # 按照 dirs 顺序寻找路径 next_node = path(cur_node[0], cur_node[1]) if maze[next_node[0]][next_node[1]] == 0: # 若是能够走 stack.append(next_node) maze[next_node[0]][next_node[1]] = -1 # 标记为已经走过,防止死循环 break else: # 四个方向都没找到 stack.pop() # 回溯 print("没有出口") return False maze = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1, 0, 0, 1], [1, 0, 1, 1, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 1, 0, 0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 1, 0, 1, 1, 0, 1], [1, 1, 0, 0, 0, 0, 0, 1, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ] find_path(1, 1, 8, 8)