def find_immediate_common_ancestor_2(root, value1, value2): """find_immediate_common_ancestor_2 algorithm: in post-order, the stack holds all the parent node when find the first value, the parent list only shrink on the road to find the 2nd value. """ p, last_visited, immediate_ancestor = root, None, None #stack = Stack([], debug=True) stack = Stack([]) while p or stack: while p: stack.append(p) p = p.left p = stack[-1] if not p.right or p.right == last_visited: stack.pop() #^# if p.value in (value1, value2): if not immediate_ancestor: immediate_ancestor = stack[-1] else: return immediate_ancestor.value if p == immediate_ancestor: if stack: immediate_ancestor = stack[-1] #$# last_visited = p p = None else: p = p.right
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack fringe = Stack() # Fringe to manage which states to expand fringe.push(problem.getStartState()) visited = [] # List to check whether state has already been visited path=[] # Final direction list pathToCurrent=Stack() # Stack to maintaing path from start to a state currState = fringe.pop() while not problem.isGoalState(currState): if currState not in visited: visited.append(currState) successors = problem.getSuccessors(currState) for child,direction,cost in successors: fringe.push(child) tempPath = path + [direction] pathToCurrent.push(tempPath) currState = fringe.pop() path = pathToCurrent.pop() return path
class QueueTheStack: "A container with a first-in-first-out (FIFO) queuing policy." def __init__(self): self.Stack1 = Stack() self.Stack2 = Stack() "add adequate number of stacks here" "*** WRITE CODE HERE ***" def push(self,item): self.Stack1.push(item); "Enqueue the 'item' into the queue" "*** WRITE CODE HERE ***" def pop(self): while (not self.Stack1.isEmpty()): self.Stack2.push(self.Stack1.pop()) toreturn = self.Stack2.pop() while (not self.Stack2.isEmpty()): self.Stack1.push(self.Stack2.pop()) return toreturn "dequeue the 'item' from the queue" "*** WRITE CODE HERE ***" def isEmpty(self): return self.Stack1.isEmpty() "returns true if the queue is empty" "***WRITE CODE HERE***"
def depthFirstSearch(problem): stack = Stack(); parentNode = []; successors = []; visitedNodes = [] parentChildMapList = {} stack.push(problem.getStartState()) currentState = problem.getStartState() #need to remove while problem.isGoalState(currentState) is False and problem.isGoalState(currentState[0]) is False: if(currentState == problem.getStartState()): successors = problem.getSuccessors(currentState) visitedNodes.append(currentState) else: successors = problem.getSuccessors(currentState[0]) visitedNodes.append(currentState[0]) if successors != None and len(successors) > 0 : parentNode.append(currentState) for node in successors: if(visitedNodes.__contains__(node) == False and visitedNodes.__contains__(node[0]) == False): stack.push(node) parentChildMapList[node] = currentState tempCurrentNode = stack.pop() if(visitedNodes.__contains__(tempCurrentNode) == False and visitedNodes.__contains__(tempCurrentNode[0]) == False): currentState = tempCurrentNode else: currentState = stack.pop() validDirections = [] firstState = currentState while firstState != problem.getStartState(): validDirections.append(firstState[1]) firstState = parentChildMapList[firstState] validDirections.reverse() return validDirections util.raiseNotDefined()
def postorder_traverse_3(root): """postorder_traverse_3 algorithm: push/pop node to stack according to current node's state """ ns = [root, VISIT_LEFT] #(node, state) stack = Stack([], debug=True) while ns or stack: while ns: stack.append(ns) node, state = ns #ns[1] == VISIT_LEFT ns[1] = VISIT_RIGHT if node.left: ns = [node.left, VISIT_LEFT] else: ns = None ns = stack[-1] if ns[1] == VISIT_RIGHT: ns[1] = VISIT_SELF if ns[0].right: ns = [ns[0].right, VISIT_LEFT] else: ns = None elif ns[1] == VISIT_SELF: yield ns[0] stack.pop() ns = None
def depthFirstSearch(problem): successor_idx = {'dir': 1, 'state': 0, 'cost': -1} MAX_ITER = int(20000) stateStack = Stack() visitedSet = set() actionList = [] # add actions to get to the state, use pop to remove last one successorDict = {} curState = problem.getStartState() stateStack.push(curState) for it in range(MAX_ITER): if problem.isGoalState(curState): return actionList if curState not in visitedSet: successors = problem.getSuccessors(curState) successorDict[curState] = successors visitedSet.add(curState) nStateTuple = filter(lambda x: x[0] not in visitedSet, successorDict[curState]) # get next state if len(nStateTuple) == 0: stateStack.pop() actionList.pop() curState = stateStack.list[-1] else: curState = nStateTuple[0][successor_idx['state']] stateStack.push(curState) actionList.append(nStateTuple[0][successor_idx['dir']]) return []
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ #Init variables currentCoordinate = problem.getStartState() #The current coordinate we are evaluating pathToCurrentCoordinate = [] #The current list we are using and updating fringeCoordinateList = Stack() #List of current edge coordinates, can have duplications fringeCoordinateList.push(currentCoordinate) previouslyVisitedCoordinatesList = [] #List of previously visited coordinates pathsToCoordinates = Stack() #List of lists of actions pathsToCoordinates.push(pathToCurrentCoordinate) #First run through while(not problem.isGoalState(currentCoordinate) and not fringeCoordinateList.isEmpty()): #Find the next coordinate from the fringe, that we haven't visited before topFringeCoordinate = fringeCoordinateList.pop() pathToCurrentCoordinate = pathsToCoordinates.pop() while(topFringeCoordinate in previouslyVisitedCoordinatesList): topFringeCoordinate = fringeCoordinateList.pop() pathToCurrentCoordinate = pathsToCoordinates.pop() currentCoordinate = topFringeCoordinate #Hotfix for autograder if (problem.isGoalState(currentCoordinate)): break; #Add new fringe coordinates to the list, and update the action lists as appropriate successors = problem.getSuccessors(currentCoordinate) for successor in successors: fringeCoordinateList.push(successor[0]) newActionList = list(pathToCurrentCoordinate) #Copy list newActionList.append(successor) pathsToCoordinates.push(newActionList) #Mark that we have visited the current coordinate previouslyVisitedCoordinatesList.append(currentCoordinate) result = [] for action in pathToCurrentCoordinate: result.append(action[1]) return result
def depthFirstSearch(problem): from collections import defaultdict from util import Stack initial_node=problem.getStartState() current_node=defaultdict(list) current_node[initial_node].append("No parent") current_node[initial_node].append("No direction") stack=Stack() stack.push(current_node) current_node=stack.pop() direction_list={} Child=current_node.keys() Parent=current_node.values()[0] visited_list={} while (problem.isGoalState(Child[0]) is not True): if(Child[0] in visited_list.keys()): current_node=stack.pop() Child=current_node.keys() Parent=current_node.values()[0] else: visited_list[Child[0]]=Parent[0] direction_list[Child[0]]=Parent[1] Successor_node=problem.getSuccessors(Child[0]) for index in range(len(Successor_node)): temp_dict=defaultdict(list) temp_dict[Successor_node[index][0]].append(Child[0]) temp_dict[Successor_node[index][0]].append(Successor_node[index][1]) #print"The temp dict values are",temp_dict stack.push(temp_dict) #print " The heap of queue is",priority_queue.heap current_node=stack.pop() #print "The current node is",current_node Child=current_node.keys() Parent=current_node.values()[0] visited_list[Child[0]]= Parent[0] direction_list[Child[0]]=Parent[1] backtracking =[] path = Child[0] backtracking.append(direction_list[path]) path = visited_list[path] print "The path is",path while (path!= problem.getStartState()): backtracking.append(direction_list[path]) path = visited_list[path] backtracking.reverse() return backtracking util.raiseNotDefined()
def depthFirstSearch(problem): "Search the shallowest nodes in the search tree first. [p 81]" from util import Stack BFS1 = Stack() Moves = [] Visited = [] Final = [] NewState = (0, (problem.getStartState(), 'Start', 0)) #print CurrentState BFS1.push([NewState]) while not BFS1.isEmpty(): NewState = BFS1.pop() if problem.isGoalState(NewState[0][1][0]): Final = NewState break if Visited.count(NewState[0][1][0]) == 0: #print NewState for item in enumerate(problem.getSuccessors(NewState[0][1][0])): #print item BFS1.push([item] + NewState) Visited.append(NewState[0][1][0]) for nodes in Final: Moves.append(nodes[1][1]) Moves.reverse() Moves.remove('Start') #print Moves return Moves
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" '''util.raiseNotDefined()''' from util import Stack path=[] closedList=[] cost=0 fringe = Stack() node=[path, cost ,problem.getStartState()] fringe.push(node) while (1): if fringe.isEmpty(): raise Exception, 'no solutiion' newState=fringe.pop() if problem.isGoalState(newState[2]): return newState[0] if newState[2] not in closedList: closedList.append(newState[2]) for x in problem.getSuccessors(newState[2]): fringe.push([newState[0]+[str(x[1])],newState[1]+x[2],x[0]])
def find_immediate_common_ancestor_5(root, value1, value2): """find_immediate_common_ancestor_5 algorithm: pre-order traversal with value for each level """ if not root: return ancestor, immediate_ancestor_level = {}, -1 stack = Stack([(root, 0)]) while stack: p, level = stack.pop() #^# ancestor[level] = p if p.value in (value1, value2): if immediate_ancestor_level == -1: immediate_ancestor_level = level - 1 else: return ancestor[immediate_ancestor_level].value if immediate_ancestor_level > level - 1: immediate_ancestor_level = level - 1 #$# if p.right: stack.append((p.right, level+1)) if p.left: stack.append((p.left, level+1))
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" stateStack = Stack() state = problem.getStartState() state = [(state, "Stop", 0)] stateStack.push(state) while not problem.isGoalState(state[len(state) - 1][0]): state = stateStack.pop() successors = problem.getSuccessors(state[len(state) - 1][0]) for successor in successors: if successor[0] not in [position[0] for position in state]: stateStack.push(state + [successor]) return [direction[1] for direction in state]
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [p 85]. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [Fig. 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ frontier = Stack() # A helper stack of (state,route_to_state) explored_set = set() # A set of state recording the explored nodes start = problem.getStartState() frontier.push((start,list())) while not frontier.isEmpty(): current_node = frontier.pop() if problem.isGoalState(current_node[0]): return current_node[1] successors = problem.getSuccessors(current_node[0]) explored_set.add(current_node[0]) for s in successors: if s[0] not in explored_set: current_route = list(current_node[1]) current_route.append(s[1]) frontier.push((s[0],current_route)) print "No route found!" return list()
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ from util import Stack start = problem.getStartState() checkStack = Stack() checkStack.push((start,[])) visitedStates = [] while not checkStack.isEmpty(): popState, popDirection = checkStack.pop() for successors in problem.getSuccessors(popState): state, direction, cost = successors if not state in visitedStates: if problem.isGoalState(state): print state return popDirection + [direction] checkStack.push((state,popDirection+[direction])) visitedStates = visitedStates+[popState]
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack frontier=Stack() start_node = Node(problem.getStartState(), step_cost=0) explored = [] frontier.push(start_node) while not frontier.isEmpty(): node = frontier.pop() explored.append(node.state) if problem.isGoalState(node.state): return node.getPath() for child in node.getChildren(problem): if not child.state in explored: frontier.push(child)
def postorder_traverse_4(root): """postorder_traverse_4 algorithm: improve postorder_traverse_3 based on the fact that if last visited node is current node's right child, then current node should be popped up """ stack = Stack([], debug=True) node = root last_visited = None while True: # push while node: stack.append(node) node = node.left if not stack: break # top/pop node = stack[-1] if not node.right or node.right == last_visited: node = stack.pop() yield node last_visited = node # prepare next node = None else: # prepare next node = node.right
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack #: lista de nodos visitados closed = [] #: pila que hace la funcion de frontera frontier = Stack() # Recogemos el primer estado, creamos un nodo y lo # insertamos en la pila frontier.push(Node(problem.getStartState())) # iteramos hasta que no hayan nodos en la pila # o hayamos encontrado el objetivo while not frontier.isEmpty(): #: siguiente nodo a expandir node = frontier.pop() # comprobamos si el estado actual nos cumple el objetivo if problem.isGoalState(node.state): # si lo cumple, salimos del bucle break if node.state not in closed: # insertamos el estado en la lista de visitados closed.append(node.state) # recuperamos los estados sucesores for successor in problem.getSuccessors(node.state): frontier.push(Node( successor[0], node, successor[1], successor[2])) #: acciones para llegar al objetivo actions = [] # recorremos mientras haya un action en el nodo previo while node.action: actions.append(node.action) node = node.previous #mostramos el resultado antes de devolverlo #print actions[::-1] return actions[::-1]
def hanoi (n, source, helper, target): if n==1: target.push(source.pop()) else: hanoi(n-1,source,target,helper) target.push(source.pop()) hanoi(n-1,helper,source,target) print "source " print temp = Stack() while not source.isEmpty(): t = source.pop() temp.push(t) print t while not temp.isEmpty(): t = temp.pop() source.push(t) print "helper " print temp = Stack() while not helper.isEmpty(): t = helper.pop() temp.push(t) print t while not temp.isEmpty(): t = temp.pop() helper.push(t) print "target" print temp = Stack() while not target.isEmpty(): t = target.pop() temp.push(t) print t while not temp.isEmpty(): t = temp.pop() target.push(t) print print
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [2nd Edition: p 75, 3rd Edition: p 87] Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" print "the problem is ", problem from game import Directions s = Directions.SOUTH w = Directions.WEST n = Directions.NORTH e = Directions.EAST start = problem.getStartState() if problem.isGoalState(start): return [] from util import Stack statesStack = Stack() exploredSet = set([start]) tup = (start,[]) statesStack.push(tup) while not statesStack.isEmpty(): tup1 = statesStack.pop() state = tup1[0] path = tup1[1] if problem.isGoalState(state): return path successors = problem.getSuccessors(state) for succ in successors: coor = succ[0] move = succ[1] #cost = succ[2] tempPath = list(path) if not coor in exploredSet: exploredSet.add(coor) if move == 'North': tempPath.append(n) elif move == 'East': tempPath.append(e) elif move == 'South': tempPath.append(s) elif move == 'West': tempPath.append(w) statesStack.push((coor,tempPath)) return []
def find_immediate_common_ancestor(root, value1, value2): """find_immediate_common_ancestor algorithm: in post-order, the stack holds all the ancestor node. record the 2 ancestor lists and compare them. """ p = root #stack = Stack([], debug=True) stack = Stack([]) last_visited = None count_found = 0 while p or stack: while p: stack.append(p) p = p.left p = stack[-1] if not p.right or p.right == last_visited: stack.pop() #^# if p.value in (value1, value2): count_found += 1 if count_found == 1: parent_stack1 = stack[:] elif count_found == 2: common_idx = -1 min_len = len(stack) < len(parent_stack1) and len(stack) or len(parent_stack1) idx = 0 while idx < min_len: if stack[idx] == parent_stack1[idx]: common_idx = idx idx += 1 else: break return stack[common_idx].value #$# last_visited = p p = None else: p = p.right
def postorder_traverse(root): """postorder_traverse algorithm: postorder (left, right, root) is the reverse of (root, right, left) """ stack = Stack([root], debug=True) while stack: p = stack.pop() yield p if p.left: stack.append(p.left) if p.right: stack.append(p.right)
def preorder_traverse(root): """preorder traversal """ stack = Stack([root], debug=True) while stack: node = stack.pop() yield node if node.right: stack.append(node.right) if node.left: stack.append(node.left)
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in:""" loc_stack = Stack() visited_node = {} parent_child_map = {} direction_list = [] start_node = problem.getStartState() parent_child_map[start_node] = [] loc_stack.push(start_node) def traverse_path(parent_node): while True: map_row = parent_child_map[parent_node] if (len(map_row) == 2): parent_node = map_row[0] direction = map_row[1] direction_list.append(direction) else: break return direction_list while (loc_stack.isEmpty() == False): parent_node = loc_stack.pop() if (problem.isGoalState(parent_node)): pathlist = traverse_path(parent_node) pathlist.reverse() return pathlist elif (visited_node.has_key(parent_node) == False): visited_node[parent_node] = [] sucessor_list = problem.getSuccessors(parent_node) no_of_child = len(sucessor_list) if (no_of_child > 0): temp = 0 while (temp < no_of_child): child_nodes = sucessor_list[temp] child_state = child_nodes[0]; child_action = child_nodes[1]; if (visited_node.has_key(child_state) == False): loc_stack.push(child_state) parent_child_map[child_state] = [parent_node,child_action] temp = temp + 1
def DepthLimitedSearch(problem, current_max_depth): from util import Stack from util import Counter from game import Actions from game import GameStateData start_board_state=problem.getStartState() current_board_state=start_board_state list_of_actions=Stack() seen_game_states=Counter() seen_game_states.update({current_board_state: current_board_state}) while(True): current_possible_actions = problem.getActions(current_board_state) move_made=False if(problem.goalTest(current_board_state)): break if(current_max_depth <= len(list_of_actions.list)): most_recent_move=list_of_actions.pop() current_board_state= problem.getResult(current_board_state,Actions.reverseDirection(most_recent_move)) continue else: current_possible_actions = problem.getActions(current_board_state) possible_new_board_state = current_board_state if(current_possible_actions and not move_made): for i in range(len(current_possible_actions)): possible_new_board_state = problem.getResult(current_board_state,current_possible_actions[i]) print(current_possible_actions) if(possible_new_board_state not in seen_game_states.values()): #make the move and update the problem list_of_actions.push(current_possible_actions[i]) seen_game_states.update({possible_new_board_state: possible_new_board_state}) current_board_state=possible_new_board_state current_possible_actions = problem.getActions(current_board_state) #seen_game_states[seen_game_states.argMax()+1] = current_board_state continue if(not move_made): if(list_of_actions.isEmpty()): break most_recent_move=list_of_actions.pop() current_board_state= problem.getResult(current_board_state,Actions.reverseDirection(most_recent_move)) return list_of_actions.list
def depthFirstSearch(problem): from game import Directions from util import Stack South = Directions.SOUTH West = Directions.WEST East = Directions.EAST North = Directions.NORTH stop = Directions.STOP """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ ans = [] ParentNode = {} direction = {} stack = Stack() startNode = problem.getStartState() visitedList = [] stack.push(startNode) if problem.isGoalState(startNode): return stop while stack.isEmpty() == False: currentNode = stack.pop() visitedList.append(currentNode) if problem.isGoalState(currentNode): goalPath = currentNode while goalPath != startNode: ans.append(direction[goalPath]) goalPath = ParentNode[goalPath] return ans[::-1] allCurrentSuccessor = problem.getSuccessors(currentNode) for Node in allCurrentSuccessor: if not Node[0] in visitedList: stack.push(Node[0]) ParentNode[Node[0]] = currentNode direction[Node[0]] = Node[1] return stop util.raiseNotDefined()
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ from util import Stack from game import Directions s = Directions.SOUTH w = Directions.WEST n = Directions.NORTH e = Directions.EAST opened = Stack() #create an open stack start = problem.getStartState() closed = set([start]) #create a closed list with the root node 1st entry if problem.isGoalState(start): #failsafe in case root is goal return [] opened.push((start, [])) while not opened.isEmpty(): tup2 = opened.pop() #remove 1st item from open stack state = tup2[0] direction = tup2[1] if problem.isGoalState(state): return direction children = problem.getSuccessors(state) #generate children for child in children: #name both the coordinates and direction position = child[0] direct = child[1] list_of_paths = list(direction) if not position in closed: #add to closed list (if not already there) closed.add(position) #list_of_paths.append(direction) if direct == 'North': list_of_paths.append(n) elif direct == 'East': list_of_paths.append(e) elif direct == 'South': list_of_paths.append(s) elif direct == 'West': list_of_paths.append(w) #keeps track of all directions traveled in dfs opened.push((position,list_of_paths)) #add children to stack return []
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack if problem.isGoalState(problem.getStartState()): return list() ##initialize the list of actions to return, frontier and explored set frontier = Stack() listOfActions = list() ##frontier includes the state and the list of actions to get to that state to construct the node frontier.push( [problem.getStartState(),listOfActions] ) explored = set() ##looping while the frontier is not empty while not(frontier.isEmpty()): ##pop one node off the frontier, check if it is the goal state node = frontier.pop() if problem.isGoalState(node[0]): return node[1] ##add the state to the explored set if it is not the goal state explored.add(node[0]) ##looping through current state's successor states for state,action,stepCost in problem.getSuccessors(node[0]): ##add the action needed from current state to next state onto the action list oldActions = list(node[1]) oldActions.append(action) nextNode = [state, oldActions] ##push the node onto the frontier if it is unexplored if(state not in explored): frontier.push(nextNode) return None
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [p 85]. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [Fig. 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ from game import Directions from util import Stack n=Directions.NORTH s=Directions.SOUTH e=Directions.EAST w=Directions.WEST explored=[] frontier=Stack() frontierSet=[] start_node=problem.getStartState() if problem.isGoalState(start_node)==True: return [] frontier.push((start_node,[])) while frontier.isEmpty()==False: currentNode=frontier.pop() currentState=currentNode[0] actions=currentNode[1] if(problem.isGoalState(currentState)==True): return actions explored.extend(currentState) successors=problem.getSuccessors(currentState) for successor in successors: succState=successor[0] succAction=successor[1] if succState not in explored and succState not in frontierSet: frontierSet.append(succState) tempPath=list(actions) if(succAction=='North'): tempPath.append(n) elif(succAction=='East'): tempPath.append(e) elif(succAction=='South'): tempPath.append(s) elif(succAction=='West'): tempPath.append(w) frontier.push((succState,tempPath)) return []
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [2nd Edition: p 75, 3rd Edition: p 87] Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack Explored = {} Frontier = Stack() node = 0 current = problem.getStartState() Explored[current] = 1; succ = problem.getSuccessors(current) for k in succ: #print "initial push",k Frontier.push([k]); Explored[k[0]] = 1; while not (Frontier.isEmpty()): current = Frontier.pop() node = current[-1][0] #print "curr path and node",current,node,"explored status",(node in Explored),"\n" # check if done if (problem.isGoalState(node)): break succ = problem.getSuccessors(node) for k in succ: if not (k[0] in Explored): Frontier.push(current + [k]); Explored[k[0]] = 1; sol = [] #print current for k in current: sol += [k[1]] # print sol return sol
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack nodes = Stack() closed = dict() moves = list() for var in problem.getSuccessors(problem.getStartState()): state = FringeState(var[0]) state.moves.append(Directions.convToDirection(var[1])) nodes.push(state) closed[problem.getStartState()] = True while(False == nodes.isEmpty()): current_node = nodes.pop() #print "Current node:", current_node if(closed.has_key(current_node.pos)): continue if(problem.isGoalState(current_node.pos)): print "Goal reached!" moves = current_node.moves break for var in problem.getSuccessors(current_node.pos): state = FringeState(var[0]) state.moves= copy.deepcopy(current_node.moves) state.moves.append(Directions.convToDirection(var[1])) nodes.push(state) closed[current_node.pos] = True return moves
def dft(self, starting_vertex): # Print each vertex in depth-first order beginning from starting_vertex. # Create an empty set to store visited nodes. # Create an empty Stack and push the starting vertex. # While the Stack is not empty.. # pop the first vertex from the stack # if that vertex has not been visited... # Mark it as visited # Then add all of its neighbors to the back of the stack. visited = set() stack = Stack() stack.push(starting_vertex) while stack.size() > 0: vertex = stack.pop() if vertex not in visited: visited.add(vertex) print(vertex) for neighbor in self.vertices[vertex]: stack.push(neighbor)
def dft(self, starting_vertex): """ Print each vertex in depth-first order beginning from starting_vertex. """ stack = Stack() visited = set() stack.push(starting_vertex) while stack.size() > 0: current = stack.pop() if current not in visited: visited.add(current) for val in self.vertices[current]: stack.push(val) # print(visited) pass # TODO
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ visited = set() stack = Stack() stack.push(([starting_vertex], self.vertices[starting_vertex])) while stack.size(): path, vertex_set = stack.pop() print(path[-1]) visited.add(path[-1]) for vertex in vertex_set: if not vertex in visited: visited.add(vertex) stack.push((path + [vertex], self.vertices[vertex])) if vertex == destination_vertex: return path + [destination_vertex]
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ path = Stack() path.push([starting_vertex]) visited = set() while path.size() > 0: path_current = path.pop() if path_current[len(path_current) - 1] == destination_vertex: return path_current else: v = path_current[len(path_current) - 1] visited.add(v) for neighbor in self.vertices[v]: new_path = path_current.copy() new_path.append(neighbor) path.push(new_path)
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ path = [] visited = set() to_visit = Stack() to_visit.push(starting_vertex) while to_visit.size() > 0: vertex = to_visit.pop() if vertex == destination_vertex: path.append(vertex) return path if vertex not in visited: visited.add(vertex) path.append(vertex) for neighbor in self.vertices[vertex]: to_visit.push(neighbor)
def dft(row, col, matrix, visited): s = Stack() # push starting vert on the stack s.push((row, col)) # while stack is not empty while s.size() > 0: # pop the first vert v = s.pop() # destructure row, col = v # if not visited, traverse! if not visited[row][col]: # Mark visited visited[row][col] = True for neighbor in get_neighbors(row, col, matrix): s.push(neighbor) return visited
def dft(self, starting_vertex): printed_traversal = '' viewed = {} for vert in self.vertices: viewed[vert] = False stack = Stack() stack.push(starting_vertex) viewed[starting_vertex] = True while stack.size() > 0: tail = stack.pop() comma = ", " if printed_traversal != "" else "" printed_traversal += comma + str(tail) for vert in self.vertices[tail]: if not viewed[vert]: viewed[vert] = True stack.push(vert) print(printed_traversal)
def dft(self, starting_vertex): """ Print each vertex in depth-first order beginning from starting_vertex. """ #same a bft except use stack instead of queue # TODO #create stack stack = Stack() #get starting point stack.push(starting_vertex) #create set to keep track of visited visited = set() #run algo while items are present in stack while stack.size() > 0: vertex = stack.pop() if vertex not in visited: print(vertex) visited.add(vertex) for next_vert in self.get_neighbors(vertex): stack.push(next_vert)
def dft(self, starting_vertex): """ Print each vertex in depth-first order beginning from starting_vertex. """ stack = Stack() visited = set() stack.push(starting_vertex) while stack.size() > 0: vertex = stack.pop() if vertex not in visited: visited.add(vertex) print(vertex) for next_vert in self.vertices[vertex]: stack.push(next_vert) print(self.vertices)
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ path = [] s = Stack() visited = set() s.push(starting_vertex) while s.size() > 0: current = s.pop() if current not in visited: path.append(current) if current is destination_vertex: return "DFS: " + str(path) visited.add(current) for next_vertex in self.vertices[current]: s.push(next_vertex) print("DFS: Path does not exist") return None
def dft(self, starting_vertex): """ Print each vertex in depth-first order beginning from starting_vertex. """ # create the stack stack = Stack() # push the starting node stack.push(starting_vertex) # create set to track visited = set() # while the stack is not empty while stack.size() > 0: current = stack.pop() if current not in visited: print(current) visited.add(current) # get the neighbors involved for i in self.get_neighbors(current): stack.push(i)
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ s = Stack() visited = set() path = [] s.push(starting_vertex) while s.size() > 0: current_node = s.pop() if current_node == destination_vertex: path.append(current_node) return path if not current_node in visited: path.append(current_node) visited.add(current_node) for item in self.vertices[current_node]: s.push(item) return f'Could not find a path from {starting_vertex} to {destination_vertex}'
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ stack = Stack() stack.push([starting_vertex]) visited_vertices = set() while stack.size() > 0: path = stack.pop() vertex = path[-1] if vertex not in visited_vertices: if vertex == destination_vertex: return path visited_vertices.add(vertex) for next_vertex in self.vertices[vertex]: new_path = list(path) new_path.append(next_vertex) stack.push(new_path) return None
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ ####Copy and pasted from dft code above### # Need to change Print to if path[-1] == destination_vertex: and then return path ss = Stack() ss.push([starting_vertex]) visited = set() while ss.size() > 0: path = ss.pop() if path[-1] not in visited: if path[-1] == destination_vertex: return path visited.add(path[-1]) for next_vert in self.get_neighbors(path[-1]): new_path = list(path) new_path.append(next_vert) ss.push(new_path)
def dft(self, starting_vertex): """ Print each vertex in depth-first order beginning from starting_vertex. """ # initialize stack with starting vertex s = Stack() s.push(starting_vertex) # set to keep track of vertexes already seen visited = set() # while queue is not empty if we haven't seen the element frome the # queue, add to visited, print, and add neighbors to queue while s.size() > 0: vertex = s.pop() if vertex not in visited: visited.add(vertex) print(vertex) for edge in self.get_neighbors(vertex): s.push(edge)
def depthFirstSearch(problem): # queue is queue of states queue = Stack() current_state = problem.getStartState() actions = [] visited = [] queue.push((current_state, actions)) while queue: current_state, actions = queue.pop() if current_state not in visited: visited.append(current_state) if problem.isGoalState(current_state): return actions for successor in problem.getSuccessors(current_state): state, action, _ = successor newActions = actions + [action] queue.push((state, newActions)) return []
def dft(self, starting_vertex): print("\n") """ Print each vertex in depth-first order beginning from starting_vertex. """ stack = Stack() stack.push(starting_vertex) visited = set() while stack.size() > 0: # pop first path = stack.pop() # if not visited if path not in visited: print(94, path) visited.add(path) for next in self.get_neighbors(path): stack.push(next) print("\n")
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ s = Stack() s.push([starting_vertex]) while s.size() > 0: p = s.pop() l = p[-1] if l == destination_vertex: return p for n in self.get_neighbors(l): new_path = p.copy() new_path.append(n) s.push(new_path)
def dft(self, starting_vertex): print("Start DFT") # create an empty set to store visited nodes visited = set() # create an empty stack and push the starting vertex on the stack stack = Stack() stack.push(starting_vertex) # while the stack is not empty while stack.size() > 0: # pop the first vertex vertex = stack.pop() # if that vertex hasn't been visited if vertex not in visited: # mark it as visited (add to visited set) visited.add(vertex) # print vertex print(vertex) # loop through edges for neighbor in self.vertices[vertex]: # push edges to stack stack.push(neighbor)
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ s = Stack() s.push([starting_vertex]) visited = set() while s.size() > 0: current_node = s.pop() if current_node not in visited: visited.append(current_node) if current_node == destination_vertex: return visited neighbors = self.get_neighbors(current_node) for neighbor in neighbors: s.push(neighbor)
def findTransformedWord(begin_word, end_word): # create transform word from begin_word # iterate through end_word # change one letter in transform word # if tw exists in words add to path # get the last word in a path and repeat stack = Stack() stack.push([begin_word]) last = stack.pop() new_tw = list(last[-1]) for l in range(len(end_word)): new_tw[l] = end_word[l] tw = ''.join(new_tw) if tw in words: last.append(tw) stack.push(list(last)) if tw == end_word: return stack.stack[-1] return None
def dft(self, starting_vertex): """ Print each vertex in depth-first order beginning from starting_vertex. """ # create an empty stack and push the starting node ID s = Stack() s.push(starting_vertex) # create a set to store the visited nodes visited = set() # While the stack is not empty while s.size() > 0: v = s.pop() # if the current node has not been visited if v not in visited: # mark as visted. print v and add v to visited set print(v) visited.add(v) # then add all of it's neougbours onto the stack for next_node in self.vertices[v]: s.push(next_node)
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ st = Stack() st.push([starting_vertex]) visited = set() while st.size() > 0: path = st.pop() if path[-1] is destination_vertex: return path if path[-1] not in visited: visited.add(path[-1]) for next_vert in self.get_neighbors(path[-1]): new_path = list(path) new_path.append(next_vert) st.push(new_path)
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ s = Stack() v = set() s.push([starting_vertex]) while s.size() > 0: path = s.pop() print(path) last_v = path[-1] if last_v not in v: v.add(last_v) if last_v == destination_vertex: return path for n in self.get_neighbors(last_v): path_copy = path.copy() path_copy.append(n) s.push(path_copy)
def dft(self, starting_vertex): """ Print each vertex in depth-first order beginning from starting_vertex. """ s = Stack() s.push(starting_vertex) visited = set() while s.size() > 0: current_node = s.pop() if current_node not in visited: visited.add(current_node) print(current_node) for neighbor in self.get_neighbors(current_node): s.push(neighbor)
def dfs(self, starting_vertex, destination_vertex): print("BFS") visited = set() s = Stack() s.push([1]) paths = {} while(s.size() > 0): path = s.pop() v = path[-1] if(v == destination_vertex): length = len(path) if(length in paths): paths[length].append(path) else: paths[length] = [path] elif(not v in visited): visited.add(v) for neighbor in self.vertices[v]: s.push([*path, neighbor]) smallest = min(paths.keys()) return None if len(paths[smallest]) == 0 else paths[smallest] if len(paths[smallest]) > 1 else paths[smallest][0]
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ s = Stack() path = [starting_vertex] s.push(path) visited = set() while s.size() > 0: vertex = s.pop() end = vertex[-1] if end == destination_vertex: return vertex if end not in visited: visited.add(end) for neighbor in self.vertices[end]: s.push(vertex + [neighbor]) return None
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ my_stack = Stack() my_stack.push([starting_vertex]) visited = set() while my_stack.size() > 0: path = my_stack.pop() if path[-1] == destination_vertex: return path print(path[-1]) visited.add(path[-1]) for next_vertex in self.get_neighbors(path[-1]): new_path = list(path) new_path.append(next_vertex) my_stack.push(new_path)
def dft(self, starting_vertex): """ Print each vertex in depth-first order beginning from starting_vertex. """ s = Stack() s.push(starting_vertex) visited = set() while s.size() > 0: v = s.pop() if v not in visited: print(v) visited.add(v) for next_vert in self.get_neighbors(v): s.push(next_vert)
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ stack = Stack() stack.push([starting_vertex]) visited = set() while stack.size() > 0: p = stack.pop() v = p[-1] if v not in visited: if v == destination_vertex: return p visited.add(v) for next_vertex in self.get_neighbors(v): new_p = list(p) new_p.append(next_vertex) stack.push(new_p)