Beispiel #1
0
def breadthFirstSearch(problem):
  "Search the shallowest nodes in the search tree first. [p 74]"
  "*** YOUR CODE HERE ***"
  from util import Queue
  
  #util.raiseNotDefined()
  currentState = problem.getStartState()
  
  setOfExploredNodes = set([currentState])
  listofMoves = []
  successorStack = Queue()
  counter = 0;
  
  while not problem.isGoalState(currentState):
      for successor in problem.getSuccessors(currentState):          
          if successor[0] not in setOfExploredNodes:
              #print successor
              setOfExploredNodes.add(successor[0])
              successorStack.push((successor[0], listofMoves + [successor[1]]))              
      
      currentState = successorStack.pop()
      
      #setOfExploredNodes.add(currentState[0])
      listofMoves = currentState[1]
      currentState = currentState[0]
      
      counter += 1
      if counter % 100 == 0:
        print counter
        

  print listofMoves  
  return listofMoves
def breadthFirstSearch(problem):
  "Search the shallowest nodes in the search tree first. [p 74]"
  "*** YOUR CODE HERE ***"
  from util import Queue
    
  currentState = problem.getStartState()
  
  setOfExploredNodes = set([currentState])
  listofMoves = []
  successorStack = Queue()
  
  while not problem.isGoalState(currentState):
      for successor in problem.getSuccessors(currentState):          
          if successor[0] not in setOfExploredNodes:              
              if problem.isGoalState(successor[0]):  
                #print listofMoves + [successor[1]]              
                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
Beispiel #3
0
def breadthFirstSearch(problem):
    successor_idx = {'dir': 1, 'state': 0, 'cost': -1}

    MAX_ITER = int(20000)
    stateQ = Queue()
    actQ = Queue() # queues action for backtracking
    visitedSet = set()

    curState = problem.getStartState()
    visitedSet.add(curState)

    actionList = [] # add actions to get to the state, use pop to remove last one

    for it in range(MAX_ITER):
        
        if problem.isGoalState(curState):
            return actionList
        
        successors = problem.getSuccessors(curState)

        for node in successors:
            if node[successor_idx['state']] not in visitedSet:
                stateQ.push(node[successor_idx['state']])
                actQ.push(actionList + [node[successor_idx['dir']]])
                visitedSet.add(node[successor_idx['state']])

        actionList = actQ.pop()
        curState = stateQ.pop()

    return []
Beispiel #4
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"

    # Imports for tools
    from util import Queue
    from game import Directions
    import copy

    path = Queue()
    path.push((problem.getStartState(), []))
    visited = set([problem.getStartState()])

    while not path.isEmpty():
        info = path.pop()
        currentState = info[0]
        actions = info[1]
        if problem.isGoalState(currentState):
            return actions
        for successor in problem.getSuccessors(currentState):
            if not successor[0] in visited:
                visited.add(successor[0])
                if ("North" in successor):
                    actions.append(Directions.NORTH)
                elif ("East" in successor):
                    actions.append(Directions.EAST)
                elif ("South" in successor):
                    actions.append(Directions.SOUTH)
                elif ("West" in successor):
                    actions.append(Directions.WEST)
                path.push((successor[0], copy.copy(actions)))
                actions.pop()
def breadthFirstSearch(problem):
  "Search the shallowest nodes in the search tree first. [p 74]"
  "*** YOUR CODE HERE ***"
  from util import Queue
  successorsExplored = {}
  statesExplored = set()
  bfsQueue = Queue()

  for successor in problem.getSuccessors(problem.getStartState()):
    bfsQueue.push((successor, None))

  statesExplored.add(problem.getStartState())
  if(problem.isGoalState(problem.getStartState())):
    return []

  while(not bfsQueue.isEmpty()):
    currentSuccessorPair = bfsQueue.pop()
    if(currentSuccessorPair[0][0] in statesExplored):
      continue

    successorsExplored[currentSuccessorPair[0]] = currentSuccessorPair[1]
    statesExplored.add(currentSuccessorPair[0][0])
    if(problem.isGoalState(currentSuccessorPair[0][0])):
      return reconstructPath(successorsExplored, currentSuccessorPair[0])

    for successor in problem.getSuccessors(currentSuccessorPair[0][0]):
      if(successor[0] not in statesExplored):
        bfsQueue.push((successor, currentSuccessorPair[0]))

  return None
Beispiel #6
0
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    """
    closed = []
    closedSet = sets.Set(closed)
    fringe = Queue()
    for child in problem.getSuccessors(problem.getStartState()):
        path = [child[1]]
        fringe.push((child[0], path, child[2]))
    closedSet.add(problem.getStartState())
    
    while( not(fringe.isEmpty()) ):
        nodePos, nodeDir, nodeCost = fringe.pop()
        if (problem.isGoalState(nodePos)):
            return nodeDir
        if (nodePos not in closedSet):
            successors = problem.getSuccessors(nodePos)
            closedSet.add(nodePos)
            path = [nodeDir]
            for childNode in successors:
                #cost = nodeCost + childNode[2]
                path = nodeDir + [childNode[1]]
                childNode = [childNode[0], path , child[2]]
                fringe.push(childNode)

    return -1
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    startState = problem.getStartState()
    # Visited
    visited = []
    # Declare variable for queue node
    queueNode = Queue()
    # Push start state into queue
    queueNode.push((startState,[]))

    while(not queueNode.isEmpty()):
        currentState, actions = queueNode.pop()

        #if currentState not in visited:
            #visited.append(currentState)

        seccessors = problem.getSuccessors(currentState)
        print "\t" , seccessors
        for state,action,cost in seccessors:
            if state not in visited:
                if problem.isGoalState(currentState):
                    print actions
                    return actions
                visited.append(state)
                queueNode.push((state,actions + [action]))
    return []
Beispiel #8
0
def breadthFirstSearch(problem):
  "Search the shallowest nodes in the search tree first. [p 81]"
  "*** YOUR CODE HERE ***"
  from util import Queue
  
  queue = Queue()
  exploredSet = set()
  pathConstructDict = {}
  
  #print "Start's successors:", problem.getSuccessors(problem.getStartState())

  #add start to exploredSet, and check if it is the goal 
  exploredSet.add(problem.getStartState())
  if(problem.isGoalState(problem.getStartState())):
    return []
    
  for successor in problem.getSuccessors(problem.getStartState()):
    #print successor
    queue.push((successor, None))

  while(not queue.isEmpty()):
    expansion = queue.pop()
    if(expansion[0][0] in exploredSet):
      continue

    exploredSet.add(expansion[0][0])
    pathConstructDict[expansion[0]] = expansion[1]

    if(problem.isGoalState(expansion[0][0])):
      return pathConstructor(expansion[0], pathConstructDict)

    for successor in problem.getSuccessors(expansion[0][0]):
      queue.push((successor, expansion[0]))
Beispiel #9
0
def breadthFirstSearch(problem):
  "Search the shallowest nodes in the search tree first. [p 81]"
  "*** YOUR CODE HERE ***"
  from util import Queue
  from game import Directions

  state = 0
  action = 1

  cstate = problem.getStartState()
  if (problem.isGoalState(cstate)):
          return []

  q = Queue()
  visited = []
  q.push((cstate, []))

  while(not q.isEmpty()):
      cstate, path = q.pop()
      visited.append(cstate)

      for x in problem.getSuccessors(cstate):
          npath = path + [x[action]]

          if(visited.count(x[state]) != 0):
              continue

          if (problem.isGoalState(x[state])):
              return npath

          nstate = x[state]
          visited.append(x[state])
          q.push((nstate, npath))

  print("Path is not found")
Beispiel #10
0
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    """

    from util import Queue
    from game import Directions
    
    actions = []
    
    frontier = Queue()
    frontier.push((problem.getStartState(), [], 0))
    visited = []

    while (frontier.isEmpty() == False):
        (currentS, currentP, currentC) = frontier.pop()
        if (problem.isGoalState(currentS) == True):
            actions = currentP
            break
        if (visited.count(currentS) == 0):
            visited.append(currentS)
            successors = problem.getSuccessors(currentS)
            for i in range(0,len(successors)):
                (neighbor, direction, cost) = successors[i]
                if (visited.count(neighbor) == 0):
                    frontier.push((neighbor, (currentP +[direction]), (currentC + cost)))
    print actions
    return actions

    util.raiseNotDefined()
Beispiel #11
0
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    """
    "*** YOUR CODE HERE ***"
    queue = Queue()
    explored = []
    
    queue.push((problem.getStartState(), [])) #what in the queue is the (state, path)
    explored.append(problem.getStartState())
    while not queue.isEmpty():
        tuple = queue.pop()
        currentPath = tuple[1]
        
        
        if problem.isGoalState(tuple[0]):
            return currentPath
                    
        suc = problem.getSuccessors(tuple[0])
        for triple in suc:
            if explored.__contains__(triple[0]):
                continue
            explored.append(triple[0])
            path = currentPath + [triple[1]]
            queue.push((triple[0], path))
Beispiel #12
0
def breadthFirstSearch(problem):
    "Search the shallowest nodes in the search tree first. [p 81]"
    from util import Queue
    BFS1 = Queue()
    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 breadthFirstSearch(problem):
def buildMazeDistanceMap(position, gameState):
    """
      Use BFS to build a map that stores maze distances between position and each point in the layout

    """
    x, y = position
    walls = gameState.getWalls()
    assert not walls[x][y], 'position is a wall: ' + str(position)

    # initialization
    distanceMap = {}
    queue = Queue()
    distance = 0
    queue.push(position)

    while not queue.isEmpty():
    	currPos = queue.pop()

    	if currPos not in distanceMap:
    		distanceMap[currPos] = distance

    		for pos in Actions.getLegalNeighbors(currPos, walls):
    			queue.push(pos)

    	distance += 1

    return distanceMap
def breadthFirstSearch(problem):
  """
  Search the shallowest nodes in the search tree first.
  [2nd Edition: p 73, 3rd Edition: p 82]
  """
  "*** YOUR CODE HERE ***"
  from util import Queue

  fila = Queue()
  colorir = []
  acoes = []
  inicial = (problem.getStartState(),None,None,0)
  "Tupla formada por (Estado atual, Estado Pai, Aчуo, Custo)"
  fila.push(inicial)
  colorir.append(inicial)

  while fila.isEmpty() == False:
    noAtual = fila.pop()
    
    if problem.isGoalState(noAtual[0]):
      return gerarCaminho(noAtual)
    else:
      for item in problem.getSuccessors(noAtual[0]):
        est = item[0]
        aco = item[1]
        cus = item[2]
        if est not in colorir:
          colorir.append(est)
          tupla = (est,noAtual,aco,cus)
          fila.push(tupla)
Beispiel #15
0
def breadthFirstSearch(problem):    

    """
    Search the shallowest nodes in the search tree first.
    """
    "*** YOUR CODE HERE ***"
    from util import Queue

    # fringe
    fringe = Queue()
    # closed set
    closed = set([])

    fringe.push((problem.getStartState(), []))

    while True:
        if fringe.isEmpty() == True:
            print 'fail to find a path to the goal state'
            return []
        else:
            node = fringe.pop()
        if problem.isGoalState(node[0]) == True:
            return node[1]
        if node[0] not in closed:
            closed.add(node[0])
            actionsSoFar = node[1]
            for successor in problem.getSuccessors(node[0]):
                newActions = actionsSoFar[:]
                newActions.append(successor[1])
                fringe.push((successor[0], newActions))
Beispiel #16
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue

    queueOpen = Queue()

    rootNode = SearchNode(problem.getStartState(), None, None, 0, 0)

    if problem.isGoalState(rootNode.position):
        return []

    queueOpen.push(rootNode)
    visited = {}
    #visited;
    #cvorovi = [pocetni];

    while not queueOpen.isEmpty():
        #ako je cvor u visited -> continue
        #stavi cvor u visited
        #za svakog sljedbenika: ako nije u visited, dodaj ga u cvorove
        currentNode = queueOpen.pop()
        if currentNode.position in visited:
            continue
        if problem.isGoalState(currentNode.position):
            return currentNode.backtrack()
        visited[currentNode.position] = True
        for succ in expand(problem, currentNode):
            if succ.position not in visited:
                temp = SearchNode(succ.position, currentNode, succ.transition, succ.cost, 0)
                queueOpen.push(temp)
Beispiel #17
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"   
    path = list()
    parentChild = list()
    print "Problem: ", problem
    print "Start:", problem.getStartState()
    print "Is the start a goal?", problem.isGoalState(problem.getStartState())
    print "Start's successors:", problem.getSuccessors(problem.getStartState())

    if problem.isGoalState(problem.getStartState()):
        return None
    explored = list()
    frontier = Queue()
    frontier.push(problem.getStartState())
    while (not frontier.isEmpty()):
        state = frontier.pop()
        #print "Current state: ", state
        explored.append(state)
        if (problem.isGoalState(state)):
            #print "Found..."
            path = backtracking(problem, state, parentChild)
            return path
        for successor in problem.getSuccessors(state):
            #print "Successor: ", successor
            if (not successor[0] in explored):
                parentChild.append((state, successor[1], successor[0]))
               
                frontier.push(successor[0])
    return None
Beispiel #18
0
def breadthFirstSearchNormal2(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    actionListMap = []
    visitedList = {}
    startState = problem.getStartState()
    q = Queue()
    q.push(startState)
    visitedList[startState] = [None, None]
    while not q.isEmpty():
        targetState = q.pop()
        isGoal = problem.isGoalState(targetState)
        if isGoal == None:
            actionList = buildActionListFromBFSResult(visitedList,startState, targetState)
            actionListMap.append((targetState, actionList))
        elif isGoal:
            actionList = buildActionListFromBFSResult(visitedList,startState, targetState)
            actionListMap.append((targetState, actionList))
            print "Meet Goal"
            return actionListMap
        else:
            for successor in problem.getSuccessors(targetState):
                state = successor[0]
                action = successor[1]
                if state not in visitedList.keys():
                    visitedList[state] = [targetState, action]
                    q.push(state)
Beispiel #19
0
 def __init__(self, position, scaredTimer, game_state, n):
     self.ds = Queue()
     self.position = position
     self.scaredTimer = scaredTimer
     self.game_state = game_state
     self.n = n
     self.visited = {}
     for i in range(n):
         self.visited[i] = []
Beispiel #20
0
def breadthFirstSearch(problem):
    from collections import defaultdict
    from util import Queue
    initial_node=problem.getStartState()
    
    current_node=defaultdict(list)
    current_node[initial_node].append("No parent")
    current_node[initial_node].append("No direction")
    queue=Queue()
    queue.push(current_node)
    current_node=queue.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=queue.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])
                queue.push(temp_dict)

            current_node=queue.pop()
            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()
Beispiel #21
0
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    """
    "*** YOUR CODE HERE ***"
    from util import Queue
    #: lista de nodos visitados
    closed = []
    #: pila que hace la funcion de frontera
    frontier = Queue()
    # 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()
        #print "\nNodo actual: ", node.state
        #print "\nCola: ", frontier.imprime()
        #print "\nVisitados: ", visited

        #while (raw_input(">>> ") != ""):
        #    pass

        # 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):
                # si el estado sucesor no esta en la frontera, lo encapsulamos
                # y lo itroducimos
                frontier.push(Node(
                                successor[0],
                                node,
                                successor[1],
                                successor[2]))

        
        #print frontier

    #: 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]
Beispiel #22
0
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    [2nd Edition: p 73, 3rd Edition: p 82]
    """
    "*** YOUR CODE HERE ***"
    from util import Queue
    fringe = Queue()
    visited = set()
    startNode = problem.getStartState()
    startNode = (startNode,"",0)
    start = Child()
    start.create(startNode,[],0,None)
    fringe.push(start)
    while fringe.list:

        node = fringe.pop()

        if problem.isGoalState(node.getCoord()):
            return node.getPath()
        visited.add(node.getNode()[0])
        children = problem.getSuccessors(node.getCoord())

        for childNode in children:
            child = Child()
            child.create(childNode,node.getPath(),1,node)
            child.addElmt(child.getNode()[1])
            if child.getCoord() not in visited and child.getCoord() not in map(Child.getCoord,fringe.list):
                fringe.push(child)
    return None
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    [2nd Edition: p 73, 3rd Edition: p 82]
    """
    "*** YOUR CODE HERE ***"
    from util import Queue
    
    fringe = Queue()
    successors = []
    state = (problem.getStartState(), "")
    fringe.push(state)
    visited = set()
    while problem.isGoalState(state[0]) == False:
        #print "state = %r, visited = %r " % (state[0],visited)
        if state[0] not in visited:
            successors = problem.getSuccessors(state[0])
            visited.add(state[0])
            for successor in successors:
                pos, dir, cost = successor
            #if pos not in visited:
                fringe.push((pos,state[1]+dir+' '))
        state = fringe.pop()    
        #print state[0], successors
    return state[1].split()
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    start = problem.getStartState()
    
    from util import Queue
    fringe = Queue()
    fringe.push([(start, 'Start', 1)])
    
    result = None
    expanded = [problem.getStartState()]
    
    while result == None:
      currentPath = fringe.pop()
      currentState = currentPath[-1]
      
      if problem.isGoalState(currentState[0]):
        result = currentPath
        continue
      
      succ = problem.getSuccessors(currentState[0])
      
      for state in succ:
        if state[0] not in expanded:
          expanded.append(state[0])
          new_list = currentPath[:]
          new_list.append(state)
          fringe.push(new_list)
    
    steps = []
    for state in result[1:]:
      steps.append(state[1])
      
    return steps  
Beispiel #25
0
 def getMinimaxValues(self, gameState, agentIndex, isRed, expandTimeout):
     startTime = time.time()
     if(PRINTDEBUG): print("Expanding nodes...")
     
     # two queues to deepen minimax
     curExpand = Queue()
     nextExpand = Queue()
     
     # create and enqueue the first node
     rootNode = MinimaxNode(None, gameState, agentIndex, self.delegate, self.ignoreIndices)
     curExpand.push(rootNode)
     nodesExpanded = 1
     depthExpanded = 0
     
     minimaxValues = []
     
     # bfs expanding nodes
     while(True):
         while(not curExpand.isEmpty()):
             toExpand = curExpand.pop()
             toExpand.expand()
             for child in toExpand.children:
                 nextExpand.push(child)
                 nodesExpanded += 1
             if(time.time() - startTime > expandTimeout):
                 break
         if(time.time() - startTime > expandTimeout):
             break
         depthExpanded += 1
         curExpand = nextExpand
         nextExpand = Queue()
         minimaxValues = []
         for childNode in rootNode.children:
             mmaxValue = childNode.calculateMinimaxValue(isRed, self.impatience)
             minimaxValues.append((childNode.action, mmaxValue))
     
     timeTaken = time.time() - startTime
     if(PRINTDEBUG): print("Expanded " + str(nodesExpanded) + " nodes to a depth of " + str(depthExpanded) + "in " + str(timeTaken) + " seconds.")
     
     
     return minimaxValues
Beispiel #26
0
def breadthFirstSearch(problem):
    queue = Queue() ; parentNode = []; successors = []; visitedNodes = []
    parentChildMapList = {}
    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)
            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):
                queue.push(node)
                parentChildMapList[node] = currentState
        tempNode = queue.pop()
        if((visitedNodes.__contains__(tempNode) == False and visitedNodes.__contains__(tempNode[0]) == False)):
            currentState = tempNode
        else:
            currentState = queue.pop()
            
    validDirections = []
    firstState = currentState


    while firstState != problem.getStartState():
            validDirections.append(firstState[1])
            firstState = parentChildMapList[firstState]
            
        
    validDirections.reverse()
    return validDirections
    util.raiseNotDefined()
Beispiel #27
0
def breadthFirstSearch(problem):
  """
  Search the shallowest nodes in the search tree first.
  [2nd Edition: p 73, 3rd Edition: p 82]
  """
  "*** YOUR CODE HERE ***"
  from game import Directions
  from util import Queue
  Explored = {}
  Frontier = Queue()
  
  node = 0
  current = problem.getStartState()
  #print "bfs first state", current
  succ = problem.getSuccessors(current)
  for k in succ:
    #print "initial push",k
    Frontier.push([k]);

  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
      Explored[node] = 1;
      if (len(Explored)%100) == 0:
          print "ex",len(Explored)
      #print node
      #Explored[node[0]] = 1;
      succ = problem.getSuccessors(node)
      for k in succ:
          if not (k[0] in Explored):
              if not (Frontier.isPresent(current + [k])):
                Frontier.push(current + [k]);
 
  sol = []
  for k in current:
    sol += [k[1]]

  #print current
  #print "action sol", sol
  return  sol
Beispiel #28
0
def breadthFirstSearch(problem):
    from util import Queue
    q = Queue()
    q.push((problem.getStartState(),[]))
    expanded = []
    while not q.isEmpty():
        top = q.pop()
        if problem.isGoalState(top[0]):
            return top[1]
        successors = problem.getSuccessors(top[0])
        for successor in successors:
            if not successor[0] in expanded:
                q.push((successor[0], top[1]+[successor[1]]))
                expanded.append(top[0])
    return []
Beispiel #29
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    
    loc_queue = Queue()
    visited_node = {}
    parent_child_map = {}
    direction_list = [] 
       
    start_node = problem.getStartState()
    parent_child_map[start_node] = []
    loc_queue.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_queue.isEmpty() == False):
        
        parent_node = loc_queue.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_queue.push(child_state)
                    if (parent_child_map.has_key(child_state) == False):
                        parent_child_map[child_state] = [parent_node,child_action]
                    temp = temp + 1
def breadthFirstSearch(problem):
    from game import Directions
    from util import Queue
    traces=[]
    StartState=problem.getStartState()
    fringe =Queue()
    closed = set()
    temp=problem.getSuccessors(StartState)
    for i in temp:  
        fringe.push((i,[]))
    closed.add(StartState)
    solution=[]
    s = Directions.SOUTH
    w = Directions.WEST
    n = Directions.NORTH
    e = Directions.EAST
    while fringe:
        node=fringe.list[-1]
        state=node[0][0]
        if not problem.isGoalState(state):
                    fringe.pop()
                    'if state in corners:'
                    'traces=traces+[node[1]+[node[0]]]'
                    if not state in closed:
                        temp= problem.getSuccessors(state)
                        if temp==[]:
                            closed.add(state)
                        else:
                            for i in temp:
                                if not i[0][0] in closed:
                                        fringe.push((i,node[1]+[node[0]]))
                            closed.add(state)
        else:
            path=node[1]+[node[0]]
            for i in path:
                if i[1]=='South':
                    solution.append(s)
                else:
                    if i[1]=='West':
                        solution.append(w)
                    else:
                        if i[1]=='North':
                            solution.append(n)
                        else:
                            if i[1]=='East':
                                solution.append(e)
            return solution
Beispiel #31
0
    def get_all_social_paths(self, user_id):
        """
        Takes a user's user_id as an argument

        Returns a dictionary containing every user in that user's
        extended network with the shortest friendship path between them.

        The key is the friend's ID and the value is the path.
        """
        # implement BFS where id is the destination
        print("start of paths")
        visited = {}  # Note that this is a dictionary, not a set
        # !!!! IMPLEMENT ME
        if user_id not in self.friendships:
            return visited
        qq = Queue()
        qq.enqueue([user_id])

        # While queue is not empty:
        while qq.size() > 0:
            # dequeue the first vertex
            path = qq.dequeue()
            v = path[-1]
            # check if it is visited
            # if not visited
            if v not in visited:

                visited[v] = path
                # enqueue all neighbors
                for friend in self.friendships[v]:

                    path_copy = path.copy()
                    path_copy.append(friend)
                    qq.enqueue(path_copy)

                # enqueue the copy

        return visited
Beispiel #32
0
def earliest_ancestor(ancestors, starting_node):
    queue = Queue()
    current_node = starting_node
    relationships = {}
    for node in ancestors:
        if node[1] not in relationships:
            relationships[node[1]] = set()
        relationships[node[1]].add(node[0])
    if starting_node in relationships:
        queue.enqueue(relationships[current_node])
    else:
        return -1
    while True:
        relations = queue.dequeue()
        current_node = min(relations)
        if current_node not in relationships:
            return current_node
        else:
            queue.enqueue(relationships[current_node])
Beispiel #33
0
    def bfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing the shortest path from
        starting_vertex to destination_vertex in
        breath-first order.
        """
        # pass  # TODO

        # QUEUE
        # Create a queue
        q = Queue()
        # Enqueue A PATH TO the starting vertex
        q.enqueue([starting_vertex])
        # Create a set to store visited vertices
        visited = set()
        # While the queue is not empty...
        while q.size() > 0:
            # Dequeue the first PATH
            path = q.dequeue()
            # GRAB THE VERTEX FROM THE END OF THE PATH
            v = path[-1]
            # Check if it's been visited
            # If it hasn't been visited...
            if v not in visited:
                # CHECK IF IT'S THE TARGET
                if v == destination_vertex:
                    # IF SO, RETURN THE PATH
                    return path
                # Mark it as visited
                visited.add(v)
                # Enqueue all it's neighbors to back of the queue
                for neighbor in self.get_neighbors(v):
                    # MAKE A COPY OF THE PATH
                    copy = path.copy()
                    # ADD NEIGHBOR TO BACK OF PATH
                    copy.append(neighbor)
                    # ENQUEUE THE COPY
                    q.enqueue(copy)
Beispiel #34
0
    def find_new_room(self):
        # print('find_new_room')
        # implement bfs to find path to nearest unseen room
        
        # def bfs(self, starting_vertex, destination_vertex):
        # """
        # Return a list containing the shortest path from
        # starting_vertex to destination_vertex in
        # breath-first order.
        # """

        # # initialize queue with starting vertex
        q = Queue()
        q.enqueue((self.current_room, []))
        
        # # set to keep track of vertexes already seen
        visited = set()

        # # while queue is not empty
        while q.size() > 0:
        #     # get path and vertex
            room, path = q.dequeue()
            # print(path)
        #     print(path)
        #     print(type(path))
        #     # if room has not been seen, return path
            if room.id not in self.seen:
                return path
            # else, add vertex to visited
            elif room.id not in visited:
                visited.add(room.id)      
                # and add paths to the queue for each edge 
                for exit in room.get_exits():
                    path_copy = path.copy()
                    path_copy.append(exit)
                    q.enqueue((room.get_room_in_direction(exit), path_copy))
        
        raise ValueError('Room not found')
Beispiel #35
0
    def bft(self, starting_vertex):
        """
        Print each vertex in breadth-first order
        beginning from starting_vertex.
        """
        # # Create a queue and enqueue starting vertex
        # qq = Queue()
        # qq.enqueue([starting_vertex])
        # # Create a set of traversed vertices
        # visited = set()
        # # While queue is not empty:
        # while qq.size() > 0:
        #     # dequeue/pop the first vertex
        #     path = qq.dequeue()
        #     # if not visited
        #     if path[-1] not in visited:
        #         # DO THE THING!
        #         print(path[-1])
        #         # mark as visited
        #         visited.add(path[-1])
        #         # enqueue all neighbors
        #         for next_vert in self.get_neighbors(path[-1]):
        #             new_path = list(path)
        #             new_path.append(next_vert)
        #             qq.enqueue(new_path)

        # Why not do this instead?
        # After doing the later functions I see....
        qq = Queue()
        qq.enqueue(starting_vertex)
        visited = set()
        while qq.size() > 0:
            vertex = qq.dequeue()
            if vertex not in visited:
                print(vertex)
                visited.add(vertex)
                for next_vert in self.get_neighbors(vertex):
                    qq.enqueue(next_vert)
Beispiel #36
0
def breadthFirstSearch(problem):
    from util import Queue

    frontier = Queue()
    explored = []
    actions = []

    class node:
        def __init__(self, path, dad, action):
            self.path = path
            self.dad = dad
            self.action = action

    start = node(problem.getStartState(), '', '')
    frontier.push(start)

    while frontier.isEmpty() == False:
        path = frontier.pop()
        successors = problem.getSuccessors(path.path)
        explored.append(path)

        for vertex in successors:
            achou = False
            for path_ex in explored:
                if vertex[0] == path_ex.path:
                    achou = True

            if achou == False:
                successor = node(vertex[0], path.path, vertex[1])
                frontier.push(successor)
                if problem.isGoalState(successor.path):
                    while len(explored) > 0:
                        ant = explored.pop()
                        if ant.path == successor.dad:
                            actions.append(successor.action)
                            successor = ant
                    actions.reverse()
                    return actions
Beispiel #37
0
    def get_all_social_paths(self, user_id):
        """
        Takes a user's user_id as an argument

        Returns a dictionary containing every user in that user's
        extended network with the shortest friendship path between them.

        The key is the friend's ID and the value is the path.
        """
        visited = {}  # Note that this is a dictionary, not a set
        #visited = set()
        # Create an empty queue and enqueue A PATH TO the starting vertex ID.
        q = Queue()
        # Create a Set to store visited vertices.
        path = [user_id]
        q.enqueue(path)
        # While the queue is not empty...
        while q.size() > 0:
            # Dequeue from the front of the line, this is our current path.
            current_path = q.dequeue()
            # current_node is the last thing in the path
            current_node = current_path[-1]
            # Check if we've visited yet, if not:
            if current_node not in visited:
                # mark as visited
                #visited.add(current_node)
                visited[current_node] = current_path

                # get the current node's friends
                friends = self.get_friends(current_node)
                # iterate over the friends
                for friend in friends:
                    # add the neighbor to the path
                    friend_path = current_path.copy()
                    friend_path.append(friend)
                    # enqueue the neighbor's path
                    q.enqueue(friend_path)
        return visited
Beispiel #38
0
def earliest_ancestor(ancestors, starting_node):
    g = Graph()
    for pair in ancestors:
        g.add_vertex(pair[0])
        g.add_vertex(pair[1])
        g.add_edge(pair[1], pair[0])
    # do a BFS (storing the path)
    q = Queue()
    # enqueue a path to starting node
    q.enqueue([starting_node])
    # creating a set to store visited
    visited = set()
    # no parents set to -1
    # initializing parents
    earliest_ancestor = -1
    while q.size() > 0:
        # gets the first path in the queue
        path = q.dequeue()
        # getting last node in the path
        v = path[-1]
        # check if it has been visited, and if not ->
        if v not in visited:
            #mark it as visited
            visited.add(v)
            # check if path(v) is less than parent meaning if there was no path it would be the parent
            # or length is longer than 1
            if ((v < earliest_ancestor) or (len(path) > 1)):
                # update V with the new NODE
                earliest_ancestor = v
            # enqueue a path to all its neighbors
            for neighbor in g.get_neighbors(v):
                # make a copy of the path
                copy = path.copy()
                # append the neighbor
                copy.append(neighbor)
                # enqueue the copy
                q.enqueue(copy)
    return earliest_ancestor
Beispiel #39
0
    def bfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing the shortest path from
        starting_vertex to destination_vertex in
        breath-first order.
        """
        # Create an empty queue
        # Add A PATH TO the starting vertex_id to the queue
        # Create an empty set to store visited nodes
        # While the queue is not empty...
        # Dequeue, the first PATH
        # GRAB THE LAST VERTEX FROM THE PATH
        # CHECK IF IT'S THE TARGET
        # IF SO, RETURN THE PATH
        # Check if it's been visited
        # If it has not been visited...
        # Mark it as visited
        # Then add A PATH TO all neighbors to the back of the queue
        # (Make a copy of the path before adding)

        queue = Queue()

        queue.enqueue([starting_vertex])

        visited = set()

        while queue.size() > 0:
            path = queue.dequeue()
            vertex = path[-1]

            if vertex not in visited:
                if vertex == destination_vertex:
                    return path
                visited.add(vertex)
                for next_vertex in self.get_neighbors(vertex):
                    new_path = list(path)
                    new_path.append(next_vertex)
                    queue.enqueue(new_path)
Beispiel #40
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"

    explored = set()
    rootNode = [problem.getStartState(), list()]

    from util import Queue
    queueNode = Queue()

    queueNode.push(rootNode)

    while not queueNode.isEmpty():

        currentNode = queueNode.pop()
        currentState = currentNode[0]
        currentPath = currentNode[1]

        explored.add(currentState)

        if problem.isGoalState(currentState):
            return currentPath

        else:
            children = problem.getSuccessors(currentState)

            for child in children:
                childState = child[0]

                # Converts a tuple into list.
                childPath = list(currentPath)

                childPath.append(child[1])

                if childState not in explored:
                    queueNode.push([child[0], childPath])

    raise Exception, 'No solutions found'
def find_nearest_unvisited(player, visited):
    room_id = player.cur_room
    neighbors = g.get_neighbors(room_id)
    q = Queue()

    # FORMAT OF QUEUE: [ [directions], [room_ids] ]
    # Initialize queue
    for direction in neighbors:
        if neighbors[direction] == '-1':
            # Return to main calling function
            print('Found next unvisited room 1 move away.')
            return [direction]
        else:
            # [directions to new location, new room id]
            room_id = neighbors[direction]
            q.enqueue([[direction], [room_id]])

    # START SEARCH
    while q.size() > 0:
        directions, room_ids = q.dequeue()
        last_room_id = room_ids[-1]
        # Get neighbors
        neighbors = g.get_neighbors(last_room_id)
        neighbors_keys = list(neighbors.keys())
        random.shuffle(neighbors_keys)
        for direction in neighbors_keys:
            r_id = neighbors[direction]
            if r_id == '-1':
                directions.append(direction)
                print(
                    f"Found next unvisited room {len(directions)} moves away.")
                return directions
            elif r_id not in room_ids:
                new_directions = list(directions)
                new_directions.append(direction)
                new_room_ids = list(room_ids)
                new_room_ids.append(r_id)
                q.enqueue([new_directions, new_room_ids])
Beispiel #42
0
    def get_all_social_paths(self, user_id):
        """
        Takes a user's user_id as an argument

        Returns a dictionary containing every user in that user's
        extended network with the shortest friendship path between them.

        The key is the friend's ID and the value is the path.
        """

        # Uper

        visited = {}  # Note that this is a dictionary, not a set
        queue = Queue()

        # add the user_id to an array and throw it into the queue
        queue.enqueue([user_id])

        # traverse through the graph
        while queue.size() > 0:
            cur_path = queue.dequeue()
            node = cur_path[-1]

            # check if we've visisted the node
            if node not in visited:
                # mapping visisted node w/current path to dict
                visited[node] = cur_path

                # grabbing all the neighbors
                friends = self.friendships[node]
                for friend in friends:
                    # add friend to path
                    copy_path = [*cur_path, friend]
                    # enqueue copy of current path + new node
                    queue.enqueue(copy_path)

        # returns list of users
        return visited
Beispiel #43
0
def earliest_ancestor(ancestors, starting_node):
    # build a graph
    graph = Graph()
    # go over a set of vertices and make nodes
    for pair in ancestors:
        # create the vertexes
        # for the specific id
        # create and check to see if its already in
        if pair[0] not in graph.vertices:
            graph.add_vertex(pair[0])
        if pair[1] not in graph.vertices:
            graph.add_vertex(pair[1])
        # create the edges
        graph.add_edge(pair[1], pair[0])

    # initialize queue
    queue = Queue()
    queue.enqueue([starting_node])
    # keep track of the longest path to figure out
    longest_path = []

    while queue.size() > 0:
        vertex_path = queue.dequeue()

        if len(vertex_path) > len(longest_path):
            longest_path = vertex_path
        if len(vertex_path) == len(longest_path):
            if vertex_path[-1] < longest_path[-1]:
                longest_path = vertex_path

        for neighbors in graph.get_neighbors(vertex_path[-1]):
            temp_path = vertex_path.copy()
            temp_path.append(neighbors)
            queue.enqueue(temp_path)
    if len(longest_path) <= 1:
        return -1
    else:
        return longest_path[-1]
Beispiel #44
0
    def bfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing the shortest path from
        starting_vertex to destination_vertex in
        breath-first order.
        """
        #Create a queue
        #Enqueue a path to the starting vertex
        #Create a set to store visited vertices
        #While the queue is not empty
        #Dequeue the first path
        #Grab the vertex from the end of the path
        #Check if it has been visited
        #Check if its the target if so return the path
        #if it hasnt been visited
        #mark it as visited
        #enqueue a path to all its neighbors
        #make a copy of the path
        #enqueue the copy

        queue = Queue()
        visited = set()
        path = [starting_vertex]
        queue.enqueue(path)

        while queue.size() > 0:
            path = queue.dequeue()
            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)
                    queue.enqueue(new_path)
Beispiel #45
0
    def bfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing the shortest path from
        starting_vertex to destination_vertex in
        breath-first order.


        plan --

        new queue
        add starting vert to queue
        make a set for visited verts
        
        while set is not empty
            deque the vert
            if this vert has not been visited
                add it to the set
                add neighbors to the back of the queue

        """
        the_queue = Queue()
        the_queue.enqueue([starting_vertex])
        visited_verts = set()

        while the_queue.size() > 0:
            the_path_2destination = the_queue.dequeue()
            vertex = the_path_2destination[-1]

            if vertex not in visited_verts:
                if vertex == destination_vertex:
                    return the_path_2destination
            
            visited_verts.add(vertex)

            for next_vert in self.vertices[vertex]:
                new_path = list(the_path_2destination)
                new_path.append(next_vert)
                the_queue.enqueue(new_path)
def traverse_all_rooms(player):
    visited = {}
    visited_path = []
    queue = Queue()
    queue.enqueue(player.current_room.id)

    while queue.size() > 0:
        if len(visited) == len(world.rooms):
            return visited

        room_id = queue.dequeue()
        visited = add_to_visited(room_id, visited)

        if len(visited_path) > 0:
            prev_room_id = visited_path[-1][0]
            prev_room_dir = reverse_direction(visited_path[-1][1])
            visited[room_id][prev_room_dir] = prev_room_id

        choices = possible_exits(room_id, player, visited)

        if choices:
            choice = random.choice(choices)
            player.travel(choice)
            visited[room_id][choice] = player.current_room.id
            visited_path.append([room_id, choice])

        else:
            choice = prev_room_dir
            player.travel(choice)
            if visited_path:
                visited_path.pop()
            else:
                traversal_path.append(choice)
                return visited

        traversal_path.append(choice)
        queue.enqueue(player.current_room.id)
        print(visited_path)
Beispiel #47
0
    def get_all_social_paths(self, user_id):
        """
        Takes a user's user_id as an argument

        Returns a dictionary containing every user in that user's
        extended network with the shortest friendship path between them.

        The key is the friend's ID and the value is the path.

        Implemented as a bfs since we want shortest paths.
        """

        visited = {}  # Note that this is a dictionary, not a set
        # instantiate the queue
        q = Queue()

        # intialize the path list and put it on the queue
        # per rubric, path consisting of only the user is valid
        path = [user_id]
        q.enqueue(path)

        # while the queue is not empty
        while q.size() > 0:
            # get the first path from the queue
            cur_path = q.dequeue()
            # and its last entry
            new_user_id = cur_path[-1]
            # search paths of unvisited users
            if new_user_id not in visited:
                visited[new_user_id] = cur_path

                friends = self.get_friends(new_user_id)
                for friend in friends:
                    path_copy = list(cur_path)
                    path_copy.append(friend)
                    q.enqueue(path_copy)

        return visited
Beispiel #48
0
def bfs(graph, starting_vertex):
    """
    Return a list containing the longest path 
    from starting_vertex  
    """
    earliest_an = None
    # Create an empty queue and enqueue A PATH TO the starting vertex ID
    q = Queue()
    initial_path = [starting_vertex]
    q.enqueue(initial_path)
    # Create a Set to store visited vertices
    visited = set()
    # While the queue is not empty...
    while q.size() > 0:
        # Dequeue the first PATH
        path = q.dequeue()
        # save the length of the path
        path_length = len(path)
        # Grab the last vertex from the PATH
        last_vert = path[-1]
        # If that vertex has not been visited...
        if last_vert not in visited:
            # Mark it as visited...
            visited.add(last_vert)
            # Then add A PATH TO its neighbors to the back of the
            for v in graph.vertices[last_vert]:
                # COPY THE PATH
                path_copy = path[:]
                # APPEND THE NEIGHOR TO THE BACK
                path_copy.append(v)
                q.enqueue(path_copy)
                # If the new path is longer than previous path
                # Save the longer path as earliest_ancestor
                if len(path_copy) > path_length:
                    earliest_an = path_copy
    if earliest_an:
        return earliest_an[-1]
    return -1
Beispiel #49
0
    def bfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing the shortest path from
        starting_vertex to destination_vertex in
        breath-first order.
        """
        # Create an empty queue and enqueue A PATH TO the starting vertex ID
        q = Queue()
        path = [starting_vertex]
        q.enqueue(path)
        # Create a Set to store visited vertices
        visited = set()

        # While the queue is not empty...
        while q.size() > 0:
            # Dequeue the first PATH
            path = q.dequeue()
            # Grab the last vertex from the PATH
            last_vert = path[-1]

            # If that vertex has not been visited...
            if last_vert not in visited:

                # CHECK IF IT'S THE TARGET
                if last_vert == destination_vertex:
                    # IF SO, RETURN PATH
                    return path

                # Mark it as visited...
                visited.add(last_vert)
                
                # Then add A PATH TO its neighbors to the back of the queue
                for next_vert in self.get_neighbors(last_vert):
                    # COPY THE PATH
                    new_path = [x for x in path]
                    new_path.append(next_vert)
                    # APPEND THE NEIGHOR TO THE BACK
                    q.enqueue(new_path)
Beispiel #50
0
    def bfs(self, starting_vertex, destination_vertex):
        # Breadth First can find shortest path
        # create the queue, breadth first traversal requires a queue
        # enqueue the starting vertex in a list
        # create the visited set to keep track of visited nodes
        q = Queue()
        q.enqueue([starting_vertex])
        visited = set()

        # while the queue still has items
        while q.size() > 0:
            # grab the first item in the queue
            path = q.dequeue()
            # 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 enqueue the new paths
                for next_vert in self.get_neighbors(vert):
                    path_copy = list(path)
                    path_copy.append(next_vert)
                    q.enqueue(path_copy)

        # if we get here, there was no path from start to destination
        return None
Beispiel #51
0
    def get_all_social_paths(self, user_id):
        """
		Takes a user's user_id as an argument

		Returns a dictionary containing every user in that user's
		extended network with the shortest friendship path between them.

		The key is the friend's ID and the value is the path.
		"""
        visited = {}  # Note that this is a dictionary, not a set

        # use queue
        qq = Queue()

        # add user to queue
        qq.enqueue([user_id])

        # while there's a queue
        while qq.size() > 0:

            # dequeue first vert
            path = qq.dequeue()

            # if not visited
            other = path[-1]
            if other not in visited:

                # PROCESS IT
                visited[other] = path

                # full copy the path
                james = self.friendships[other]
                for who in james:
                    new_path = list(path)
                    new_path.append(who)
                    qq.enqueue(new_path)

        return visited
Beispiel #52
0
    def get_all_social_paths(self, user_id):
        """
        Takes a user's user_id as an argument

        Returns a dictionary containing every user in that user's
        extended network with the shortest friendship path between them.

        The key is the friend's ID and the value is the path.
        """
        # Create a Queue
        q = Queue()
        # Enqueue a path to user_id
        q.enqueue([user_id])
        # Create a dictionary for key/value pairs
        visited = {}  # Note that this is a dictionary, not a set
        # While the queue is not empty...
        while q.size() > 0:
            # Dequeue the first path
            path = q.dequeue()
            # Grab the vertex from the end of the path
            v = path[-1]
            # Check if its been visited
            # IF it has not been visited...
            if v not in visited:
                if v is not user_id:
                    # Do the thing
                    visited[v] = path
                # Enqueue a path to all its neighbors
                for neighbor in self.friendships[v]:
                    if neighbor not in visited:
                        # Make a copy of the path
                        copy = path.copy()
                        # Append the neighbor
                        copy.append(neighbor)
                        # Enqueue the copy
                        q.enqueue(copy)

        return visited
Beispiel #53
0
    def find_words(starting_word, ending_word):
        visited = set()
        pending = Queue()

        pending.enqueue([starting_word])

        while len(pending) > 0:
            path = pending.dequeue()
            vert = path[-1]

            if vert == ending_word:
                return path

            if vert not in visited:
                visited.add(vert)
                for neighbor in get_neighbors(vert):
                    new_path = list(path)
                    new_path.append(neighbor)
                    pending.enqueue(new_path)
Beispiel #54
0
    def bfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing the shortest path from
        starting_vertex to destination_vertex in
        breath-first order.
        """
        qq, path = Queue(), []
        qq.enqueue(starting_vertex)

        while qq:
            vertex = qq.dequeue()
            if vertex in path:
                continue
            path.append(vertex)
            for adj_vertex in self.vertices[vertex]:
                qq.enqueue(adj_vertex)
            if vertex == destination_vertex:
                return path
        return path
Beispiel #55
0
    def bft(self, starting_vertex):
        """
        Print each vertex in breadth-first order
        beginning from starting_vertex.
        """
        self.vertex_search(starting_vertex)

        pending = Queue()
        visited = set()

        if starting_vertex in self.vertices:
            pending.enqueue(starting_vertex)
        while len(pending.queue) > 0:
            vertex = pending.dequeue()
            if vertex and vertex not in visited:
                visited.add(vertex)
                print(vertex)
                for neighbor in self.get_neighbors(vertex):
                    pending.enqueue(neighbor)
Beispiel #56
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
   # create a stack to bfs and save the path
    bfs = Queue()
    rs = []
    # to vistie node 
    visited = []
    #Get start state
    startState = problem.getStartState()

    # print(startState)

    if(problem.isGoalState(startState)):
        return []

        
    bfs.push((startState,[]))

    while(not bfs.isEmpty()):
       
        pos,rs = bfs.pop()
       
        # if current is goal
        if (problem.isGoalState(pos)):
            return rs
        if (pos not in visited):
            visited.append(pos)
            #get next states

            next = problem.getSuccessors(pos)
            #push next states into queue to wait to visite
            for item in next:
                if(item[0] not in visited):
                    bfs.push((item[0],rs + [item[1]]))
    
    #if no solution:
    return []
Beispiel #57
0
def traverseBack():
    q = Queue()
    roomID = player.currentRoom.id
    visited = [roomID]
    exits = graph[roomID]
    for exit in exits.items():
        q.enqueue([exit[1]])

    while True:
        temp = q.dequeue()
        visited.append(temp[-1])
        roomID = temp[-1]
        exits = graph[roomID]
        if '?' in exits.values():
            executePath(temp)
            return
        for exit in exits.items():
            if exit[1]  not in visited:
                q.enqueue([*temp, exit[1]])
Beispiel #58
0
    def get_all_social_paths(self, user_id):
        """
        Takes a user's user_id as an argument

        Returns a dictionary containing every user in that user's
        extended network with the shortest friendship path between them.

        The key is the friend's ID and the value is the path.
        """
        visited = {}  # Note that this is a dictionary, not a set
        # !!!! IMPLEMENT ME

        # instantiate a queue for BFS
        q = Queue()
        # enqueue starting user
        q.enqueue([user_id])

        # while the queue is not empty:
        while q.size() > 0:
            # dequeue the first path
            path = q.dequeue()
            # grab the last user from the path
            user = path[-1]
            # if that user has not been visited...
            if user not in visited:
                # add the user as a key to the visted dictionary, and add its
                #. path as the value
                visited[user] = path
                # then add a path to its neighbors
                for friend in self.friendships[user]:
                    # make a copy of the path
                    new_path = path.copy()
                    # append the neighbor to the back of the new path
                    new_path.append(friend)
                    # enqueue the new path
                    q.enqueue(new_path)

        return visited
Beispiel #59
0
    def get_all_social_paths(self, user_id):
        """ Takes a user's user_id as an argument. Returns a dictionary containing every user in that user's extended network with the shortest friendship path between them. The key is the friend's ID and the value is the path."""

        # use BFT to get to each person in the connected component
        # use BFS to get to the shortest path to each component

        def get_shortest_path(origin, destination):
            """Helper function that gets the shortest path to a destination node via BFS"""
            q2 = Queue()
            q2.enqueue([origin])
            visited = set()

            while q.size() > 0:
                path = q2.dequeue()
                vertex = path[-1]
                if vertex not in visited:
                    visited.add(vertex)
                    if vertex == destination:
                        return path
                    else:
                        for neighbor in self.friendships[vertex]:
                            q2.enqueue([*path, neighbor])
            return [origin, destination]

        q = Queue()
        q.enqueue(self.friendships[user_id])
        visited = {}  # Note that this is a dictionary, not a set
        while q.size() > 0:
            friendships = q.dequeue()
            # print(f'current friendships: {friendships}')
            # for each friend in friendships
            for friend in friendships:
                # friendships is a set of integers
                if friend not in visited and friend != user_id:
                    visited[friend] = get_shortest_path(user_id, friend)
                    q.enqueue(self.friendships[friend])
                # looks like you'll have to do a traversal of that connected component
        return visited
Beispiel #60
0
def calcMazeDistance(point_1, point_2, walls):
    x1, y1 = point_1
    x2, y2 = point_2
    assert not walls[x1][y1], 'point1 is a wall: ' + str(point_1)
    assert not walls[x2][y2], 'point2 is a wall: ' + str(point_2)

    from util import Queue
    from game import Actions
    state_queue = Queue()
    initial_path = []
    state_queue.push((point_1, initial_path))
    visited_states = []
    visited_states.append(point_1)
    while state_queue.isEmpty() == False:
        state = state_queue.pop()
        if state[0] == point_2:
            return len(state[1])
        successors = []
        for action in [
                Directions.NORTH, Directions.SOUTH, Directions.EAST,
                Directions.WEST
        ]:
            x, y = state[0]
            dx, dy = Actions.directionToVector(action)
            nextx, nexty = int(x + dx), int(y + dy)
            if not walls[nextx][nexty]:
                nextState = (nextx, nexty)
                cost = 1
                successors.append((nextState, action, cost))

        for successor in successors:
            if successor[0] in visited_states:
                continue
            visited_states.append(successor[0])
            new_path = state[1][:]
            new_path.append(successor[1])
            state_queue.push((successor[0], new_path))
    return 0