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
Example #2
0
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
Example #3
0
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
Example #4
0
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 ***"
    path = Stack()
    explored = []
    def depthSearch(state):        
        
        explored.append(state)#record that this node is explored
        
        if problem.isGoalState(state): #check if goal
            return True  #return to the higher level of the "depthSearch" 
        
        suc = problem.getSuccessors(state)  #get a list of triples(successor, action, stepCost)   
                                            #the successor is the next state
                                            #e.g. [((5, 4), 'South', 1), ((4, 5), 'West', 1)] 
#         suc = [triple for triple in suc if not triple[0] in explored]
#         for triple in suc:
#             explored.append(triple[0])
                
        for triple in suc: # for every triple(successor, action, stepCost)  
            if explored.__contains__(triple[0]):#check if the state is searched
                continue           
            if depthSearch(triple[0]): #the recursive
                path.push(triple[1])    # if the lower level return true, record the action
                return True            # which means this level also has found goal state
         
        return False   

    depthSearch(problem.getStartState()) #The first call
    
    route = []
    while (not path.isEmpty()):
        action = path.pop()
        #print action
        route.append(action) #return a list of action
    return route
Example #5
0
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 []
Example #6
0
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()
Example #7
0
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]
Example #8
0
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()
Example #9
0
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
Example #10
0
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)
Example #11
0
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]])
Example #12
0
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 getNodes(dsType, problem):
        if dsType == DataStructureType.STACK:
            from util import Stack
            nodes = Stack()
            nodes.push(Node([problem.getStartState()], [], 0, 0))
            return nodes
        elif dsType == DataStructureType.QUEUE:
            from util import Queue
            nodes = Queue()
            nodes.push(Node([problem.getStartState()], [], 0, 0))
            return nodes
        elif dsType == DataStructureType.PRIORITY_QUEUE:
            from util import PriorityQueue
            nodes =  PriorityQueue()
            nodes.push(Node([problem.getStartState()], [], 0,0),0)
            return nodes
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
Example #15
0
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]
Example #16
0
def inorder_traverse(root):
    """inorder traversal
    """
    stack = Stack([], debug=True)
    node = root

    while True:
        # push
        while node:
            stack.append(node)
            node = node.left

        if len(stack) == 0: break

        # pop
        node = stack.pop()

        yield node

        # next
        node = node.right
Example #17
0
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]
Example #18
0
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
    fringe = Stack()
    visited = set()
    path = Stack()
    start = problem.getStartState()
    visited.add(start)
    path.push(start)
    children = problem.getSuccessors(start)

    for child in children:
        fringe.push(child)
        ds = DFSRec(problem,fringe,visited,path)
        if ds != None:
            break

    pathToGoal = directions(ds)
    return pathToGoal
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))
Example #20
0
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 []
Example #21
0
def depthFirstSearch(problem):
  """
  Search the deepest nodes in the search tree first [p 74].
  
  Your search algorithm needs to return a list of actions that reaches
  the goal.  Make sure to implement a graph search algorithm [Fig. 3.18].
  
  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
     
  currentState = problem.getStartState()
  
  setOfExploredNodes = set([currentState])
  listofMoves = []
  successorStack = Stack()
  
  while not isGoalState.problem(currentState):
      for successor in problem.getSuccessors(currentState):          
          if successor[0] not in setOfExploredNodes:
              if problem.isGoalState(successor[0]):
                return listofMoves + [successor[1]]
              
              setOfExploredNodes.add(successor[0])
              successorStack.push((successor[0], listofMoves + [successor[1]]))
      
      currentState = successorStack.pop()      
      listofMoves = currentState[1]
      currentState = currentState[0]
      


  return None
Example #22
0
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
Example #23
0
 def __init__(self, game_state, n, blocks=None, position=None):
     self.ds = Stack()
     self.game_state = game_state
     self.position = position if position else self.game_state.getPacmanPosition()
     self.n = n
     ghosts = [search(GhostMovesProblem(round_tuple(ghost.getPosition()),ghost.scaredTimer, game_state, n)) for ghost in self.game_state.getGhostStates()]
     if blocks:
         self.blocks = blocks
     else:
         self.blocks = {}
         for i in range(n):
             self.blocks[i] = []
             for gn in ghosts:
                 self.blocks[i].extend([round_tuple(t) for t in gn[i]])
Example #24
0
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
Example #25
0
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()
Example #26
0
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 [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 []            
Example #28
0
def postorder_traverse_2(root):
    """postorder_traverse_2

    algorithm:
      improve postorder_traverse by using 2 stacks and make the output in the rite order.
    """
    stack1, stack2 = Stack([], debug=True), Stack([])
    stack1.append(root)
    while stack1:
        p = stack1.pop()
        stack2.append(p)
        if p.left: stack1.append(p.left)
        if p.right: stack1.append(p.right)

    while stack2:
        p = stack2.pop()
        yield p
Example #29
0
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
Example #30
0
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
Example #31
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()
        s.push([starting_vertex])
        # Create a Set to store visited vertices
        visited = set()
        # While the queue is not empty...
        while s.size() > 0:
            # Dequeue the first PATH
            path = s.pop()
            # Grab the last vertex from the PATH
            s = path[-1]
            # If that vertex has not been visited...
            if s not in visited:
                # CHECK IF IT'S THE TARGET
                  # IF SO, RETURN PATH
                if s == destination_vertex:
                    return path

                # Mark it as visited...
                visited.add(s)

                # Then add A PATH TO its neighbors to the back of the queue
                  # COPY THE PATH
                  # APPEND THE NEIGHOR TO THE BACK

                for next_vert in self.get_neighbors(s):
                    new_path = list(path)  # Copy the list
                    new_path.append(next_vert)
                    s.push(new_path)
        # If we got here, we didn't find it
        return None
Example #32
0
    def dft(self, starting_vertex):
        # create a stack (DFT requires a stack)
        s = Stack()
        # push the starting index
        s.push(starting_vertex)
        # create a blank set to hold the nodes that have been visited
        visited = set()

        # run a loop while the stack still has items
        while s.size() > 0:

            # pop the first item and store it in a variable
            v = s.pop()

            # check if the node has already been visited or not
            if v not in visited:
                # if not, print it and
                # add it to the set
                print(v)
                visited.add(v)

                for next_vert in self.get_neighbors(v):
                    # push new vertices for all the neighbors
                    s.push(next_vert)
Example #33
0
    def dft(self, starting_vertex):
        """
        Print each vertex in depth-first order
        beginning from starting_vertex.
        """
        # Create empty set
        vertices = set()
        # Create empty Stack
        stack = Stack()

        stack.push(starting_vertex)

        # Iterate all the levels and identify the vertices
        while stack.size() > 0:
            vertex = stack.pop()

            # Check if node visited
            if vertex not in vertices:
                print(vertex)
                vertices.add(vertex)

                for next_vertex in self.vertices[vertex]:
                    if next_vertex not in vertices:
                        stack.push(next_vertex)
Example #34
0
    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()
        visited = set()
        # while the queue is not empty

        stack.push([starting_vertex])
        #create a set to store the visited vertices

        while stack.size() > 0:
            # dequeue the first path
            path = stack.pop()
            # grab the last index from the PATH
            vertex = path[-1]
            # check if the vertex has not been visited
            if vertex not in visited:
                # is this vertex the target?
                if vertex == destination_vertex:
                    # return path
                    return path
                # mark it as visited
                visited.add(vertex)
                # then add a path to its neighbors  to the back of the queue
                for nextVertex in self.get_neighbors(vertex):
                    # make a copy of the path
                    pathCopy = list(path)
                    # append a neighbor to the back of the path
                    pathCopy.append(nextVertex)
                    # enqueue out new path
                    stack.push(pathCopy)
        # return none
        return None
Example #35
0
 def dft(self, starting_vertex):
     """
     Print each vertex in depth-first order
     beginning from starting_vertex.
     """
     # Create a queue/stack as appropriate
     stack = Stack()
     # Put the starting point in that
     stack.push(starting_vertex)
     # Make a set to keep track of where we've been
     visited = set()
     # While there is stuff in the queue/stack
     while stack.size() > 0:
         #    Pop the first item
         vertex = stack.pop()
         #    If not visited
         if vertex not in visited:
             #       DO THE THING!
             print(vertex)
             visited.add(vertex)
             #       For each edge in the item
             for next_vert in self.get_neighbors(vertex):
                 #           Add that edge to the queue/stack
                 stack.push(next_vert)
Example #36
0
 def dfs(self, starting_vertex, destination_vertex):
     """
     Return a list containing a path from
     starting_vertex to destination_vertex in
     depth-first order.
     """
     # pass  # TODO
      # create a stack
     s = Stack()
     # push a list holding the starting vertex id
     s.push([starting_vertex])
     # created an empty visited set
     visited = set()
     # while the stack is not empty
     while s.size() > 0:
         # pop to the path
         vertex = s.pop()
         # set a vert to the last item in the path
         last_vertex = vertex[-1]
         # if vert is not in visited
         if last_vertex not in visited:
             # if vert is equal to target value
             if last_vertex == destination_vertex:
                 # return path
                 return vertex
             # add vert to visited set
             visited.add(last_vertex)
             # loop over next vert in vertices at the index of vert
             for next_vert in self.vertices[last_vertex]:
                 # set a new path equal to a new list of the path (copy)
                 path = list(vertex)
                 # append next vert to new path
                 path.append(next_vert)
                 # push the new path
                 s.push(path)
     return None
Example #37
0
def dft(graph, starting_node):
    stack = Stack()
    stack.push((starting_node, 0))
    visited = set()

    # could build a dictionary or set or
    # track two variables as we go

    visited_pairs = set()

    while stack.size() > 0:
        current_pair = stack.pop()
        visited_pairs.add(current_pair)
        current_node = current_pair[0]
        current_distance = current_pair[1]

        if current_node not in visited:
            visited.add(current_node)

            parents = graph.getNeighbors(current_node)

            for parent in parents:
                parent_distance = current_distance + 1
                stack.push((parent, parent_distance))
    longest_distance = 0
    aged_one = -1

    for pair in visited_pairs:
        node = pair[0]
        distance = pair[1]

        if distance > longest_distance:
            longest_distance = distance
            aged_one = node

        return aged_one
Example #38
0
def build_traversal_path(player, room_graph):
    stack = Stack()
    stack.push((player.current_room.id, 'null'))
    visited = {}

    while stack.size() > 0:

        t = stack.pop()
        vertex = t[0]
        direction = t[1]

        if vertex not in visited:
            visited[vertex] = direction

            if direction != 'null':
                if player_can_move(player, direction, vertex) is not False:
                    player.travel(direction)
                    traversal_path.append(direction)
                else:
                    path = find_path(player.current_room.id, vertex)
                    walk_the_path(path, player)

            for i in room_graph[vertex][1]:
                stack.push((room_graph[vertex][1][i], i))
Example #39
0
    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()
        visited = set()
        path = [starting_vertex]
        stack.push(path)

        while stack.size() > 0:
            path = stack.pop()
            vertex = path[-1]

            if vertex == destination_vertex:
                return path

            if vertex not in visited:
                visited.add(vertex)
                for neighbor in self.get_neighbors(vertex):
                    new_path = path[:]
                    new_path.append(neighbor)
                    stack.push(new_path)
Example #40
0
 def dft(self, starting_vertex):
     """
     Print each vertex in depth-first order
     beginning from starting_vertex.
     1. create a stack and visted set
     2. starting with starting node, push it
     3. while there is items in stack, do the following
     4. pop the first item 
     5. if not visited
     6. list it in visted set
     7. get all negiboring vertices
     8. push all negiboring vertices
     9. print the poped item
     """
     s = Stack()
     visited = set()
     s.push(starting_vertex)
     while s.size() > 0:
         poped = s.pop()
         if poped not in visited:
             visited.add(poped)
             for each in self.get_neighbors(poped):
                 s.push(each)
             print(poped)
Example #41
0
    def dft(self, starting_vertex):
        """
        Print each vertex in depth-first order
        beginning from starting_vertex.

        Memorize:
        Create an empty stack and push the starting vertex ID
        Create an empty Set to store veisited vertices
        while the stack is not empty...
            Pop the first vertex
            If that vertex has not be visited...
                Mark it as visited
                Then push all of its neighbors to the top of the stack
        """
        s = Stack()
        s.push(starting_vertex)
        visited = set()
        while s.size() > 0:
            v = s.pop()
            while v not in visited:
                print(v)
                visited.add(v)
                for next_vert in self.get_neighbors(v):
                    s.push(next_vert)
Example #42
0
 def dft(self, starting_vertex):
     """
     Print each vertex in depth-first order
     beginning from starting_vertex.
     """
     # Create stack
     ss = Stack()
     # Add starting vertex to stack
     ss.push(starting_vertex)
     # Create empty set to hold items already visited
     visited = set()
     # While stack is not empty
     while ss.size() > 0:
         # Get next item from stack
         node = ss.pop()
         # Check if item has been visited already
         if node not in visited:
             # If not, print it
             print(node)
             # and add it to visited set
             visited.add(node)
             for next_node in self.get_neighbors(node):
                 # Get neighbors of node and add them to the stack to iterate through next
                 ss.push(next_node)
Example #43
0
def earliest_ancestor(ancestors, starting_node):    
    s = Stack()
    path = [[starting_node]]
    first = find_ancestors(starting_node, ancestors)
    
    # edge case: no ancestors
    if len(first) == 0:
        return -1

    s.push(first)
    path.append(first)

    while s.size() > 0:
        cur = s.pop()

        for el in cur:
            nxt = find_ancestors(el, ancestors)
            if len(nxt) > 0:
                s.push(nxt)
                path.append(nxt)

    last = min(path[-1])

    return last
Example #44
0
    def dfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing a path from
        starting_vertex to destination_vertex in
        depth-first order.
        """
        # Create an empty stack and push A PATH TO the starting vertex ID
        s = Stack()
        s.push([starting_vertex])

        # Create a Set to store visited vertices
        visited = set()

        # While the stack is not empty...
        while s.size() > 0:
            # Pop the first PATH
            path = s.pop()
            # Grab the last vertex from the PATH
            v = path[-1]
            # If that vertex has not been visited...
            if v not in visited:
                # Check if it's the target
                if v == destination_vertex:
                    # If so, return PATH
                    return path
                # Otherwise,
                else:
                    # Mark it as visited
                    visited.add(v)
                    # Then add A PATH TO its neighbors to the top of the stack
                    for next_vert in self.get_neighbors(v):
                        # _COPY_ THE PATH
                        path_copy = path.copy()
                        # APPEND THE NEIGHOR TO THE BACK
                        path_copy.append(next_vert)
                        s.push(path_copy)
Example #45
0
 def dfs(self, starting_vertex, destination_vertex):
     """
     Return a list containing a path from
     starting_vertex to destination_vertex in
     depth-first order.
     """
     # create a stack
     s = Stack()
     # push a path to the starting vertex
     s.push([starting_vertex])
     # create a set to store visited vertices
     visited = set()
     # while the stack is not empty
     while s.size() > 0:
         # pop off the first path
         path = s.pop()
         # grab the last vertex from the path
         v = path[-1]
         # check if it's been visited
         # if it hasn't been visited
         if v not in visited:
             # mark it as visited
             visited.add(v)
             # check if it's the targeted vertex
             if v == destination_vertex:
                 # if it is, return the path
                 return path
             # otherwise, push a path to all its neighbors
             # for each neighbor:
             for neighbor in self.get_neighbors(v):
                 # make a copy of current path
                 new_path = path.copy()
                 # add neighbor to the end
                 new_path.append(neighbor)
                 # push the new path
                 s.push(new_path)
Example #46
0
 def dft(self, starting_vertex):
     """
     Print each vertex in depth-first order
     beginning from starting_vertex.
     """
     # Create a stack
     s = Stack()
     # Push the starting vertex
     s.push(starting_vertex)
     # Create a set to store visited vertices
     visited = set()
     # while the stack is not empty...
     while s.size() > 0:
         # pop the first vertex
         v = s.pop()
         # Check if it's been visited
         # If it hasn't been visited...
         if v not in visited:
             # Mark it as visited
             print(v)
             visited.add(v)
             # push all it's neighbors onto the stack
             for neighbor in self.get_neighbors(v):
                 s.push(neighbor)
Example #47
0
    def dfs(self, starting_vertex, destination_vertex, visited=set()):
        """
        Return a list containing a path from
        starting_vertex to destination_vertex in
        depth-first order.
        """
        stack = Stack()

        visited = set()
        stack.push([starting_vertex])
        while stack.size() > 0:
            path = stack.pop()
            vert = path[-1]
            if vert not in visited:
                if vert == destination_vertex:
                    return path

                visited.add(vert)
            for next_vert in self.vertices[vert]:
                new_path = list(path)
                new_path.append(next_vert)
                stack.push(new_path)

        return None
Example #48
0
    def dfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing a path from
        starting_vertex to destination_vertex in
        depth-first order.
        """
        # refactoring bfs to use stack
        s = Stack()

        s.push([starting_vertex])
        visited = set()
        while s.size() > 0:
            path = s.pop()
            last_vertex = path[-1]
            if last_vertex not in visited:
                if last_vertex == destination_vertex:
                    return path
                visited.add(last_vertex)

                for n in self.get_neighbors(last_vertex):
                    new_path = list(path)  # copy the list
                    new_path.append(n)
                    s.push(new_path)
        return None
Example #49
0
    def dfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing a path from
        starting_vertex to destination_vertex in
        depth-first order.
        """
        qq = Stack()
        visited = set()
        qq.push([starting_vertex])

        while qq.size() > 0:
            path = qq.pop()
            print(f'path: {path}')
            vertex = path[-1]
            print(f'vertex: {vertex}')
            if vertex not in visited:
                if vertex == destination_vertex:
                    return path
                visited.add(vertex)
                print(f'visited: {visited}')
                for next_vert in self.vertices[vertex]:
                    new_path = list(path)  #creates a deepcopy
                    new_path.append(next_vert)
                    qq.push(new_path)
Example #50
0
    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()
        visited = set()
        stack.push([starting_vertex])
        while stack.size() > 0:
            path = stack.pop()
            current_vertex = path[-1]

            if current_vertex == destination_vertex:
                return path

            if current_vertex not in visited:
                visited.add(current_vertex)
                neighbors = self.getNeighbors(current_vertex)
                for neighbor in neighbors:
                    current_path = path[:]
                    current_path.append(neighbor)
                    stack.push(current_path)
        return []
Example #51
0
    def dft(self, starting_vertex):
        """
        Print each vertex in depth-first order
        beginning from starting_vertex.
        """

        # Create an empty stack and push the starting vertex ID
        stack = Stack()
        stack.push(starting_vertex)
        # Create an empty set to store visited vertices
        visited = set()
        # While the stack is not empty...
        while stack.size() > 0:
            # Pop  the first vertex
            v = stack.pop()
            # If that vertex has not been visited...
            if v not in visited:
                # Mark it as visited
                print(v)
                visited.add(v)
                # Then add all of its neighbors to the top of the stack
                for neigbor in self.vertices[v]:
                    # for neighbor in self.get_neighbors(vertex):
                    stack.push(neigbor)
Example #52
0
def earliest_ancestor(ancestors, starting_node):
    graph = Graph()
    for parent, child in ancestors:
        vertices = graph.vertices
        if parent not in vertices:
            graph.add_vertex(parent)
        if child not in vertices:
            graph.add_vertex(child)
        graph.add_edge(child, parent)

    s = Stack()
    s.push([starting_node])

    longest = [starting_node]
    visited = set()
    oldest = -1

    while s.size() > 0:
        path = s.pop()
        curr = path[-1]
        # breakpoint()
        if (len(path) > len(longest)) or (len(path) == len(longest)
                                          and curr < oldest):
            longest = path
            oldest = longest[-1]

        if curr not in visited:
            visited.add(curr)

            parents = graph.get_neighbors(curr)

            for parent in parents:
                new_path = path + [parent]
                s.push(new_path)

    return oldest
Example #53
0
    def dft(self, starting_vertex):
        """
        Print each vertex in depth-first order
        beginning from starting_vertex.
        """
        # create an empty stack and push the starting vertex id
        s = Stack()
        s.push(starting_vertex)
        # create a set to store our visited vertices
        visited = set()

        # while stack is not empty (len greater than 0)
        while s.size() > 0:
            # pop the first vertex
            v = s.pop()
            # if that vertex has not been visited
            if v not in visited:
                # mark as visited and print for debugging
                visited.add(v)
                print(v)
                # iterate over the child vertices of the current vertex
                for next_vertex in self.vertices[v]:
                    # push the next vertex
                    s.push(next_vertex)
Example #54
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()
        visited = set()
        path = [starting_vertex]
        s.push(path)

        while s.size() > 0:
            curr_path = s.pop()
            curr = curr_path[-1]
            if curr == destination_vertex:
                return curr_path
            if curr not in visited:
                visited.add(curr)
                neighbors = self.get_neighbors(curr)
                for neighbor in neighbors:
                    path_copy = curr_path[:]
                    path_copy.append(neighbor)

                    s.push(path_copy)
Example #55
0
    def dfs(self, starting_vertex, destination_vertex):
        # create a Stack (DFS requires a stack)
        # and push the starting vertex in a list (to keep track of the traveled path)
        # create a visited set to keep track of visited nodes
        s = Stack()
        s.push([starting_vertex])
        visited = set()
        # while the stack still has items
        while s.size() > 0:
            # grab the first item in the stack
            path = s.pop()
            # and grab the vertex from the last index in the path
            vert = path[-1]

            # if the vertex hasn't been visited
            if vert not in visited:

                # if the vertex equals our destination value,
                # return the path, we have our answer
                if vert == destination_vertex:
                    return path

                # else add the vertex to visited
                visited.add(vert)

                # loop through all remaining neighbors and
                # create a copy of the path,
                # append the new vertex for all neighbors to the path,
                # and push the new paths
                for next_vert in self.get_neighbors(vert):
                    path_copy = list(path)
                    path_copy.append(next_vert)
                    s.push(path_copy)

        # if we get here, there was no path from start to destination
        return None
Example #56
0
def earliest_ancestor2(ancestors, starting_node):
    #nodes -> people
    #edges -> when child has a parent

    #either bfs or dfs would work here
    graph = build_graph(ancestors)

    s = Stack()

    visited = set()

    s.push([starting_node])

    longest_path = [starting_node]
    aged_one = -1

    while s.size() > 0:
        path = s.pop()
        current_node = path[-1]

        # if path is longer, or path is equal but the id is smaller
        if (len(path) > len(longest_path)) or (len(path) == len(longest_path)
                                               and current_node < aged_one):
            longest_path = path
            aged_one = longest_path[-1]

        if current_node not in visited:
            visited.add(current_node)

            parents = graph.get_neighors(current_node)

            for parent in parents:
                new_path = path + [parent]
                s.push(new_path)

    return aged_one
Example #57
0
 def dfs(self, starting_vertex, destination_vertex):
     # Create an empty stack
     to_visit = Stack()
     # push A PATH TO the starting vertex ID
     to_visit.push([starting_vertex])
     # Create a Set to store visited vertices
     visited = set()
     # While the queue is not empty...
     while to_visit.size() > 0:
         # Pop the first PATH
         v = to_visit.pop()
         # Grab the last vertex from the PATH
         v2 = v[-1]
         # If that vertex has not been visited...
         if v2 not in visited:
             # CHECK IF IT'S THE TARGET
             if v2 == destination_vertex:
                 # IF SO, RETURN PATH
                 return v
         # Mark it as visited...
             visited.add(v2)
             # Then add A PATH TO its neighbors to the back of the queue
             for neighbor in self.vertices[v2]:
                 to_visit.push(v + [neighbor])
Example #58
0
    def dfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing a path from
        starting_vertex to destination_vertex in
        depth-first order.
        """        

        # Create a Stack
        ss = Stack()
        # Create a set of traversed/visited vertices
        visited = set()
        # Push a PATH to the starting vertex
        ss.push([starting_vertex])
        # while the stack is not empty..
        while ss.size() > 0:
            # Dequeue/pop the the first index/vertex
            path = ss.pop()
            # Grab the vertex from the end of the path
            last_vertex = path[-1]
            # Check if vertex (node) is visited, if not
            if last_vertex not in visited:
                # DO THE THING!! (search stop when you find something)
                print(last_vertex)
                # mark as visited
                visited.add(last_vertex)
                # enqueue/add a path to all it's neighbors
                if last_vertex == destination_vertex:
                    return path
                for next_vert in self.get_neighbors(last_vertex):
                    # Make a copy of the path
                    # new_path = path.copy()
                    new_path = list(path)
                    # append/add all neighbors
                    new_path.append(next_vert)
                    # push the copy
                    ss.push(new_path)   
Example #59
0
def dfs(starting_room, destination_room):
    stack = Stack()
    visited = set()
    stack.push([starting_room])

    while stack.size() > 0:
        path = stack.pop()
        room = path[-1]
        if room not in visited:
            if room == destination_room:
                break
            visited.add(room)
            for next_room in list(traversal_graph[room].values()):
                if next_room != '?':
                    n_path = list(path)
                    n_path.append(next_room)
                    stack.push(n_path)

    dirs = []
    for i in range(len(path) - 1):
        for direction, room in traversal_graph[path[i]].items():
            if room == path[i + 1]:
                dirs.append(direction)
    return dirs
Example #60
0
 def dft(self, starting_vertex):
     """
     Print each vertex in depth-first order
     beginning from starting_vertex.
     """
     # create a stack to hold the nodes to visit
     to_visit = Stack()
     # use this to hold visited nodes
     visited = set()
     # push the starting node to the stack
     to_visit.push(starting_vertex)
     # while the stack exists
     while to_visit.size() > 0:
         # pop the first value, hold it as "v"
         v = to_visit.pop()
         # if v isn't in the visited set
         if v not in visited:
             #print it
             print(v)
             # and add it to visited
             visited.add(v)
             # push all of it's neighbors
             for n in self.vertices[v]:
                 to_visit.push(n)