def DFS_graph(graph, v0): """ Depth-First Search graph """ vnum = graph.vertex_num() visited = [0] * vnum visited[v0] = 1 DFS_seq = [v0] st = SStack() st.push((0, graph.out_edge(v0))) while not st.is_empty(): i, edges = st.pop() if i < len(edges): v, e = edges[i] st.push((i + 1, edges)) if not visited[v]: DFS_seq.append(v) st.push((0, graph.out_edge(v))) return DFS_seq
def preorder_elements(self): t, s = self._root, SStack() while t is not None or not s.is_empty(): while t is not None: s.push(t.right) yield t.data t = t.left t = s.pop()
def entries(self): t, s = self._root, SStack() while t is not None or s.is_empty(): while t is not None: s.push(t) t = t.left t = s.pop() yield t.data.key, t.data.value t = t.right
def postorder_nonrec(t, proc): if not callable(proc): raise ValueError('proc must be a function') s = SStack() while t is not None or not s.is_empty(): while t is not None: s.push(t) t = t.left if t.left is not None else t.right t = s.pop() proc(t.data) if not s.is_empty() and s.top().left == t: t = s.top().right else: t = None
def maze_solver(maze, start, end): """ Backtracking solution , based on stack""" if start == end: print(start) return True st = SStack() mark(maze, start) st.push((start, 0)) while not st.is_empty(): pos, nxt = st.pop() for i in range(nxt, 4): nextp = pos[0] + dirs[i][0], pos[1] + dirs[i][1] if nextp == end: return True if passable(maze, nextp): st.push((pos, i + 1)) mark(maze, nextp) st.push((nextp, 0)) break print('No path found.')
def preorder_nonrec(t, proc): if not callable(proc): raise ValueError('proc must be a function') s = SStack() while t is not None and not s.is_empty(): while t is not None: proc(t.data) if t.right is not None: s.push(t.right) t = t.left t = s.pop()