def dfs(root, endState): frontier = LifoQueue() frontier.put_nowait(root) explored = set() while not frontier.empty(): state = frontier.get_nowait() explored.add(state.getState()) if endState == state.getState().getGrid(): return state for children in state.children: if children not in frontier and children not in frontier: frontier.append(children) return "Failure"
def hasCycle(self, graph): # return True if graph has cycle, else return False visited = set() for node in graph.keys(): if node not in visited: stack = Stack() stack.put(node) path = set([node]) while not stack.emtpy(): node = stack.pop() visited.add(node) for child in graph[node]: if child in path: return True if child not in visited and child in graph: stack.append(child) path.add(child) if len(visited) == len(graph): break return False
from queue import LifoQueue maxsize=4 stack=LifoQueue() i=1 #push while stack.qsize()<maxsize: stack.put(i) i+=1 print("Size:",stack.qsize()) #pop while stack.qsize()>0: print(stack.get()) print("Size:",stack.qsize()) #Method 2 from collections import deque stack = deque() #push stack.append('a') stack.append(2) print('Initial stack:',stack) #pop print(stack.pop()) print(stack.pop()) print('Stack after elements are popped:',stack)