Пример #1
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"

    from util import Queue

    #creates frontier and root node using getStartState()
    #FIFO queue with node as the only element
    frontier = Queue()
    frontier.push(problem.getStartState())

    #holds explored states
    explored = set()
    #holds final path to take
    finalPath = []
    #queue to hold next direction to take
    nextDirection = Queue()
    currState = frontier.pop()

    while not problem.isGoalState(currState):

        if currState not in explored:
            explored.add(currState)
            nextState = problem.getSuccessors(currState)

            for child, direction, cost in nextState:
                frontier.push(child)
                currPath = finalPath+[direction]
                nextDirection.push(currPath)

        currState = frontier.pop()
        finalPath = nextDirection.pop()

    return finalPath
Пример #2
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    node = Queue()  # contains state that has to be expanded
    path_traversed = Queue(
    )  # Queue to keep record of the directions from start state to current node
    traversed = []  # list of nodes that has been visited already
    path = []  # the final directions list
    ss = problem.getStartState()  # start state
    node.push(ss)
    current_node = node.pop()

    while problem.isGoalState(current_node) != True:
        if current_node not in traversed:
            traversed.append(current_node)
            children = problem.getSuccessors(
                current_node)  # getting successors as tuples
            for child, dir, cost in children:  # looping over the successors
                node.push(child)
                temp_path = path + [dir]
                path_traversed.push(temp_path)

        current_node = node.pop()
        path = path_traversed.pop()
    print "path", path
    return path

    util.raiseNotDefined()
Пример #3
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    # util.raiseNotDefined()
    from util import Queue
    q = Queue()
    q2 = Queue()
    q2.push([])
    q.push([problem.getStartState()])
    visited = []
    visited.append(problem.getStartState())
    if (problem.isGoalState(problem.getStartState())):
        return []
    x = 1
    while (q.isEmpty() == False):
        path = q.pop()
        path2 = q2.pop()
        top = path[-1]
        if (problem.isGoalState(top)):
            return path2
        successors = problem.getSuccessors(top)
        for i in range(len(successors)):
            if (successors[i][0] not in visited):
                # path.append(successors[i][1])
                addpath = list(path)
                addpath.append(successors[i][0])
                addpath2 = list(path2)
                addpath2.append(successors[i][1])
                q.push(addpath)
                q2.push(addpath2)
                visited.append(successors[i][0])
                # if(problem.isGoalState(successors[i][0])):
                #     return addpath2
    return []
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue

    states_to_expand = Queue()
    states_to_expand.push(problem.getStartState())
    visited_states = []
    path_to_goal = []
    path_to_current_state = Queue()
    current_state = states_to_expand.pop()

    flag = 1
    while flag == 1:
        if problem.isGoalState(current_state):
            break
        elif current_state not in visited_states:
            visited_states.append(current_state)
            choices_of_move = problem.getSuccessors(current_state)
            for p in range(0, len(choices_of_move)):
                choice = choices_of_move[p]
                new_position = choice[0]
                direction = choice[1]
                states_to_expand.push(new_position)
                path_to_current_state.push(path_to_goal + [direction])
        current_state = states_to_expand.pop()
        path_to_goal = path_to_current_state.pop()

    return path_to_goal

    util.raiseNotDefined()
Пример #5
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"

    from util import Queue
    L = list()
    expanded = list()
    q = Queue()
    direction = list()
    current_direction = list()
    current_coordinates = problem.getStartState()
    while ((problem.isGoalState(current_coordinates)) == False):
        for i in problem.getSuccessors(current_coordinates):
            direction = current_direction[:]
            direction.append(i[1])
            if current_coordinates not in expanded:
                expanded.append(current_coordinates)
            if i[0] not in expanded:
                q.push((i[0], direction, i[2]))

        current_state = q.pop()
        while (current_state[0] in expanded):
            current_state = q.pop()

        current_coordinates = current_state[0]
        current_direction = current_state[1]
    L = (current_state[1])
    return L
    util.raiseNotDefined()
Пример #6
0
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    """
    "*** YOUR CODE HERE ***"
    #same as DFS but implemented with Queue instead
    from util import Queue
    openlist = Queue()

    #push start state, action, and cost to openlist
    state = problem.getStartState()
    openlist.push((state, [], 0))

    #pop top off and add to closed list
    state, totalpath, totalcost = openlist.pop()
    closedlist = [state]
    isEmpty = False  #set to false initially so that we can enter loop

    #While not at goal state & not empty, search
    while ((not problem.isGoalState(state)) & (not isEmpty)):
        #grab successors of current
        successors = problem.getSuccessors(state)

        #for each successor of current, if not visited,
        for succ, action, cost in successors:
            #add to open list and visit it immediately cause we visit by level in BFS
            if (not succ in closedlist):
                openlist.push((succ, totalpath + [action], totalcost + cost))
                closedlist.append(succ)

        isEmpty = openlist.isEmpty()
        state, totalpath, totalcost = openlist.pop()
        #repeat

    return totalpath
Пример #7
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue

    startState = problem.getStartState()
    dataStructure = Queue(
    )  # Use queue as a data structure for breadthFirstSearch
    dataStructure.push(
        (problem.getStartState(), [], 0))  # push the startState on the queue
    node = dataStructure.pop()  # process the startState
    visited = []
    visited.append(node[0])  # put the startState in the list of visited nodes
    actions = []
    actions = node[1]
    cost = node[2]

    while not problem.isGoalState(
            node[0]):  # Loop till we don't reach the goal state
        successors = problem.getSuccessors(node[0])
        for successor in successors:
            if not successor[0] in visited:
                # If node has not been visited, then push the node on to the queue
                dataStructure.push((successor[0], actions + [successor[1]],
                                    cost + successor[2]))
                visited.append(
                    successor[0]
                )  # put the node to visited nodes after it has been processed
        node = dataStructure.pop()
        actions = node[1]
        cost = node[2]

    return actions
Пример #8
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 []
Пример #9
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    positions = Queue()
    pos = problem.getStartState()
    positions.push(pos)
    visited = []
    paths = Queue()
    paths.push([])
    while True:
        pos = positions.pop()
        visited.append(pos)
        path = paths.pop()
        #print(pos,len(path))
        if problem.isGoalState(pos):
            return path
        suc = problem.getSuccessors(pos)

        for i in suc:
            newpos = i[0]
            if not newpos in visited:
                path2 = path.copy()
                path2.append(i[1])
                positions.push(newpos)
                paths.push(path2)

        if positions.isEmpty():
            break

    return []
Пример #10
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    #util.raiseNotDefined()
    from game import Directions
    from util import Queue
    close = set()
    fringes = Queue()
    #Stack for father nodes doesn't fit BFS, have to enqueue the entire path
    currentState = []
    currentState.append((problem.getStartState(), None, 1))
    fringes.push(currentState)
    while (not fringes.isEmpty()):
        currentState = fringes.pop()
        close.add(currentState[-1][0])
        if (problem.isGoalState(currentState[-1][0])):
            ret = []
            for i in range(1, len(currentState)):
                ret.append(currentState[i][1])
            return ret
        successors_list_not_filtered = problem.getSuccessors(
            currentState[-1][0])
        for i in range(0, len(successors_list_not_filtered)):
            currentState_copy = currentState.copy()
            currentState_copy.append(successors_list_not_filtered[i])
            fringes.push(currentState_copy)
        #Now filter the fringes in case that new states in close set aren't counted in
        new_fringes = Queue()
        while (not fringes.isEmpty()):
            new_fringe = fringes.pop()
            if (not new_fringe[-1][0] in close):
                new_fringes.push(new_fringe)
        fringes = new_fringes
Пример #11
0
def breadthFirstSearch(problem):
    root = problem.getStartState()
    rootNode = [root, []]
    if problem.isGoalState(root):
        return []

    frontier = Queue()
    frontier.push(rootNode)

    explored = []
    print("got here")
    while not frontier.isEmpty():
        if problem.isGoalState(frontier.top()[0]):
            print("Found goal state")
            goal = frontier.pop()
            return goal[1]
        node = frontier.pop()
        if node[0] not in explored:
            explored.append(node[0])
            for child_state in problem.getSuccessors(node[0]):
                if child_state[
                        0] not in explored:  #to make more efficient make sure not in frontier too
                    child_path = node[1][:]
                    child_path.append(child_state[1])
                    frontier.push([child_state[0], child_path])
    return []
Пример #12
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 []
Пример #13
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from game import Directions
    from util import Queue

    frontiers = Queue()
    frontiers.push(problem.getStartState())
    pathToFrontiers = Queue()
    pathToFrontiers.push([Directions.STOP])
    exploredSet = list()

    while not frontiers.isEmpty():
        node = frontiers.pop()
        pathToNode = pathToFrontiers.pop()
        exploredSet.append(node)
        successors = problem.getSuccessors(node)

        for child, direction, cost in successors:
            if child not in exploredSet:
                if child not in frontiers.list:
                    if problem.isGoalState(child):
                        return (pathToNode + [direction])[1:]
                    else:
                        frontiers.push(child)
                        pathToFrontiers.push(pathToNode + [direction])

    return [Directions.STOP]
Пример #14
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"

    from util import Queue
    fringe = Queue()  # Fringe to manage which states to expand
    fringe.push(problem.getStartState())
    visited = []  # List to check whether state has already been visited
    tempPath = []  # Temp variable to get intermediate paths
    path = []  # List to store final sequence of directions
    pathToCurrent = Queue(
    )  # Queue to store direction to children (currState and pathToCurrent go hand in hand)
    currState = fringe.pop()
    while not problem.isGoalState(currState):
        if currState not in visited:
            visited.append(currState)
            successors = problem.getSuccessors(currState)
            for child, direction, cost in successors:
                fringe.push(child)
                tempPath = path + [direction]
                pathToCurrent.push(tempPath)
        currState = fringe.pop()
        path = pathToCurrent.pop()

    return path
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    from util import Queue

    explored = []

    frontier = Queue()
    all_paths = Queue()

    state = problem.getStartState()
    path = []
    while not problem.isGoalState(state):
        if state not in explored:
            # print("State to explore: {} with path {}".format(state, path))
            explored.append(state)

            for s,a,c in problem.getSuccessors(state):
                if s not in explored:
                    frontier.push(s)
                    all_paths.push(path + [a])

        state = frontier.pop()
        path = all_paths.pop()

    return path
Пример #16
0
def breadthFirstSearch(problem):
    "*** YOUR CODE HERE ***"
    bfsQueue = Queue()  # Main DFS stack
    histQueue = Queue()  # Stack which keeps track of path
    vis = []  # visited array
    way = []  # Ways returned to the pacman agent

    # starting state
    state = [(problem.getStartState(), 'Begin')]

    bfsQueue.push(state)

    # BFS Algo
    while not bfsQueue.isEmpty():
        inter_state = bfsQueue.pop()

        if not histQueue.isEmpty():
            way = histQueue.pop()

        # check if the node is visited or not
        if problem.isGoalState(inter_state[0][0]):
            break

        if (vis.count(inter_state[0][0]) == 0):
            vis.append(inter_state[0][0])
            succ_nodes = problem.getSuccessors(inter_state[0][0])

            # Find the successor nodes
            for item in succ_nodes:
                # Get the co-ordinates and the direction to reach
                co_ord, _dir = (item[0], item[1])
                bfsQueue.push([(co_ord, _dir)])
                histQueue.push(way + [_dir])

    return way
Пример #17
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

    frontier = Queue()
    explored = []
    temp_solution = Queue()
    solution = []
    frontier.push(problem.getStartState())
    node = frontier.pop()
    while problem.isGoalState(node) is False:
        if node not in explored:
            explored.append(node)
            succ = problem.getSuccessors(node)
            for state, actions, stepCost in succ:
                frontier.push(state)
                temp = solution + [actions]
                temp_solution.push(temp)
        node = frontier.pop()
        solution = temp_solution.pop()
    return solution
Пример #18
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()
Пример #19
0
 def multipleExpanding(self, current_state, depth):
     queue_fathers = Queue()
     queue_children = Queue()
     queue_fathers.push(TreeNode((current_state, []), None))
     if self.hasVisibleEnemy(current_state):
         print "searching"
         for i in range(0, depth):
             while not queue_fathers.isEmpty():
                 top_father = queue_fathers.pop()
                 temp_my_children = top_father.expand(
                     self.generateMyNextStatesIdAction(top_father.value[0]))
                 temp_enemy_children = map(
                     lambda my_child: my_child.expand(
                         self.generateNextEnemyStatesIdAction(
                             my_child.value[0])), temp_my_children)
                 temp_enemy_children = filter(lambda x: x != [],
                                              temp_enemy_children)
                 #print temp_enemy_children
                 for temp_enemy_children_group in temp_enemy_children:
                     temp_group_evals = map(
                         lambda e_state_ids_actions: self.
                         evaluateEnemyState(e_state_ids_actions.value[0]),
                         temp_enemy_children_group)
                     #print temp_group_evals
                     if temp_group_evals != []:
                         max_group_eval = max(temp_group_evals)
                         max_group_children = random.choice(
                             filter(
                                 lambda x: x[0] == max_group_eval,
                                 zip(temp_group_evals,
                                     temp_enemy_children_group)))[1]
                         #print max_group_children
                         queue_children.push(max_group_children)
             while not queue_children.isEmpty():
                 queue_fathers.push(queue_children.pop())
     while not queue_fathers.isEmpty():
         last_father = queue_fathers.pop()
         temp_my_lasts = last_father.expand(
             self.generateMyNextStatesIdAction(last_father.value[0]))
         temp_evals = map(
             lambda x: self.evaluateState(x.value[0], self.index),
             temp_my_lasts)
         if temp_evals != []:
             max_eval = max(temp_evals)
             max_evals_my_lasts = filter(lambda x: x[0] == max_eval,
                                         zip(temp_evals, temp_my_lasts))
             best_my_last = random.choice(max_evals_my_lasts)[1]
             prev_father = None
             while best_my_last.father != None:
                 prev_father = best_my_last
                 best_my_last = best_my_last.father
             if prev_father != None:
                 return prev_father.value[1][0][1]
     return random.choice(current_state.getLegalActions(self.index))
Пример #20
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from game import Directions
    from util import Stack, Queue
    import itertools
     
    closed = set([]);
    fringe = Queue();
    search_node = Queue();
    
    fringe.push([problem.getStartState(),'Stop',0])
    #search_node.push([(problem.getStartState(),'Stop',0)])
  
    while True:    
      
        if fringe.isEmpty():
            print "Failure"
            return [];
        
        node = fringe.pop(); 
        nodePath = []
        try:
            nodePath = search_node.pop();
        except IndexError: 
            pass
                
        if problem.isGoalState(node[0]):
            print "goal = ", node; 
            print "route = ", nodePath 
            route = extractActions(nodePath)
            for item in route:
                #print "item = ", item
                pass
            #return []
            return route   
        if not node[0] in closed:
            closed.add(node[0]);
            for child_node in problem.getSuccessors(node[0]):   
                newNodePath = []
                for item in nodePath :
                    newNodePath.append(item)    
                newNodePath.append(child_node)
                
                fringe.push(child_node);
                search_node.push(newNodePath)           

    util.raiseNotDefined()
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)
Пример #22
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]))
Пример #23
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
Пример #24
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()
    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()
Пример #25
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)
Пример #26
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
Пример #27
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):
Пример #28
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue

    state = problem.getStartState()
    visited = [state]
    path_dict = {}  #path dictionary {next : last} i.e. {(4, 5) : (5, 5)}
    act_dict = {}  #action dictionary {node : action} i.e. {(4, 5) : 'West'}
    actions = []
    queue = Queue()
    queue.push(state)

    while not queue.isEmpty():
        state = queue.pop()
        if problem.isGoalState(state):
            break
        for succ in problem.getSuccessors(state):
            if succ[0] not in visited:
                visited.append(succ[0])
                queue.push(succ[0])
                path_dict[succ[0]] = state
                act_dict[succ[0]] = succ[1]
    print path_dict
    print state
    while state in path_dict:
        actions.append(act_dict[state])
        state = path_dict[state]
    actions.reverse()
    return actions
Пример #29
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
Пример #30
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
Пример #31
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue as queue
    queue = queue(
    )  # Breadth First Search => First in First out strategy using queue
    explored = []  # Memorize the explored nodes
    queue.push(
        ([], problem.getStartState()))  # push the problem into queue class

    # pop from the queue until get the goal or explore all the nodes
    while not queue.isEmpty():
        path, location = queue.pop()
        explored.append(location)

        if problem.isGoalState(location):
            return path

        s = [
            x for x in problem.getSuccessors(location)
            if x[0] not in explored and x[0] not in (y[1] for y in queue.list)
        ]

        # update the path
        for item in s:
            fullpath = path + [item[1]]
            queue.push((fullpath, item[0]))

    print('Stack is empty')
    return []
Пример #32
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)
Пример #33
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    from game import Directions
    Destination = Queue()

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

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

    while not Destination.isEmpty():
        Node, Path = Destination.pop()

        if problem.isGoalState(Node):
            return Path
        if Node not in VisitedNode:
            Successor = problem.getSuccessors(Node)

            VisitedNode.append(Node)
            for location, action, cost in Successor:
                if (location not in VisitedNode):
                    Destination.push((location, Path + [action]))

    util.raiseNotDefined()
Пример #34
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    LOCATION = 0
    DIRECTION = 1

    q = Queue()
    used = set()
    cur = State(problem.getStartState(), [])  # current (location, path)
    q.push(cur)

    while not q.isEmpty():
        cur = q.pop()  # take last item from queue

        if cur.location in used:
            continue

        used.add(cur.location)  # mark as used

        if problem.isGoalState(cur.location):
            break

        for x in problem.getSuccessors(cur.location):
            if not x[LOCATION] in used:
                q.push(State(x[LOCATION], cur.path + [x[DIRECTION]]))

    return cur.path
Пример #35
0
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
Пример #36
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    # 起始节点队列
    opened = Queue()
    # 已经访问过的节点表
    closed = []
    # 得到初始节点
    opened.push((problem.getStartState(), []))
    # 开始遍历
    while not opened.isEmpty():
        # 得到当前节点
        currentNode0, currentNode1 = opened.pop()
        # 判断是否是目标节点
        if problem.isGoalState(currentNode0):
            return currentNode1
        # 如果当前节点没有访问过
        if currentNode0 not in closed:
            # 得到后继节点和运行方向以及花费代价
            expand = problem.getSuccessors(currentNode0)
            # 将当前节点加入closed表中
            closed.append(currentNode0)
            # 遍历后继节点
            for locations, directions, cost in expand:
                if (locations not in closed):
                    opened.push((locations, currentNode1 + [directions]))
    util.raiseNotDefined()
Пример #37
0
    def findPathToClosestDot(self, gameState):
        """
        Returns a path (a list of actions) to the closest dot, starting from
        gameState.
        """
        # Here are some useful elements of the startState
        startPosition = gameState.getPacmanPosition(self.index)
        food = gameState.getFood()
        walls = gameState.getWalls()
        problem = AnyFoodSearchProblem(gameState, self.index)

        "*** YOUR CODE HERE ***"
        from util import Queue
        getSucc = problem.getSuccessors
        visited = set()
        queue = Queue()
        queue.push((startPosition, []))
        while not queue.isEmpty():
            cur, path = queue.pop()
            if food[cur[0]][cur[1]]:
                return path

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

                for each in getSucc(cur):
                    if each[0] not in visited:
                        queue.push((each[0], path + [each[1]]))

        return []
Пример #38
0
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."""
    "*** 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  
Пример #40
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    from game import Directions
    opened_set = Queue()
    closed_set = set()
    meta = dict()
    root = problem.getStartState()
    meta[root] = (None, None)
    opened_set.push(root)

    while not opened_set.isEmpty():
        subtree_root = opened_set.pop()
        if problem.isGoalState(subtree_root):
            return action_path(subtree_root, meta, root)

        for (a, b, c) in problem.getSuccessors(subtree_root):
            if (a in closed_set):
                continue
            if (a not in opened_set.list):
                meta[a] = (subtree_root, b)
                opened_set.push(a)

        closed_set.add(subtree_root)
Пример #41
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))
Пример #42
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")
Пример #43
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()
Пример #44
0
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
Пример #45
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()
Пример #46
0
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
Пример #47
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))
Пример #48
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_list = Queue()
    #    closed_states = set()
    closed_states = []
    startState = problem.getStartState()
    fringe_list.push((startState, []))

    while not fringe_list.isEmpty():
        currentState = fringe_list.pop()
        goalState = problem.isGoalState(currentState[0])
        if goalState:
            return currentState[1]
        if currentState[0] not in closed_states:
            #            closed_states.update({currentState[0]})
            closed_states.append(currentState[0])
            for successor in problem.getSuccessors(currentState[0]):
                fringe_list.push(
                    (successor[0], currentState[1] + [successor[1]]))
Пример #49
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

    # the component of tree is (state, the path to the state)
    tree = Queue()
    tree.push(((problem.getStartState()), []))

    # store the visited state
    visited = []

    while (not tree.isEmpty()):
        (state, path) = tree.pop()
        if (problem.isGoalState(state)):
            break

        successors = problem.getSuccessors(state)
        for i in successors:
            if (
                    i[0] not in visited
            ):  # any state has been visited doesn't need to be visited again
                visited.append(i[0])
                tree.push((i[0], path + [i[1]]))

    return path

    util.raiseNotDefined()
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 []
Пример #51
0
def breadthFirstSearch(problem):
    '''
    dfs 랑 자료구조만 다르고 로직은 동일
    '''
    from util import Queue

    bfs_q = Queue()  # 큐 이용
    now_state = problem.getStartState()
    bfs_q.push((now_state, []))
    is_visited = []

    while not bfs_q.isEmpty():
        now_state = bfs_q.pop()

        if now_state[0] in is_visited:
            continue
        else:
            is_visited.append(now_state[0])

        if problem.isGoalState(now_state[0]):
            return now_state[1]

        for (location, direction, cost) in problem.getSuccessors(now_state[0]):
            if location not in is_visited:
                bfs_q.push((location, now_state[1] + [direction]))

    return []
Пример #52
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()
Пример #53
0
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
Пример #54
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    #Init variables
    currentCoordinate = problem.getStartState() #The current coordinate we are evaluating
    pathToCurrentCoordinate = [] #The current list we are using and updating
    
    fringeCoordinateList = Queue() #List of current edge coordinates, can have duplications
    fringeCoordinateList.push(currentCoordinate)
    
    previouslyVisitedCoordinatesList = [] #List of previously visited coordinates
    
    pathsToCoordinates = Queue() #List of lists of actions
    pathsToCoordinates.push(pathToCurrentCoordinate)
    
    while(not problem.isGoalState(currentCoordinate) and not fringeCoordinateList.isEmpty()):
        #Find the next coordinate from the fringe, that we haven't visited before
        topFringeCoordinate = fringeCoordinateList.pop()
        pathToCurrentCoordinate = pathsToCoordinates.pop()
        while(topFringeCoordinate in previouslyVisitedCoordinatesList):
            topFringeCoordinate = fringeCoordinateList.pop()
            pathToCurrentCoordinate = pathsToCoordinates.pop()
            
        currentCoordinate = topFringeCoordinate
        
        #Hotfix for autograder
        if (problem.isGoalState(currentCoordinate)):
            break;
        
        #Add new fringe coordinates to the list, and update the action lists as appropriate
        successors = problem.getSuccessors(currentCoordinate)
        for successor in successors:
            fringeCoordinateList.push(successor[0])            
            newActionList = list(pathToCurrentCoordinate) #Copy list
            newActionList.append(successor)
            pathsToCoordinates.push(newActionList)
            
        #Mark that we have visited the current coordinate
        previouslyVisitedCoordinatesList.append(currentCoordinate)
    
    result = []
    for action in pathToCurrentCoordinate:
        result.append(action[1])

    return result
Пример #55
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]
Пример #56
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"

    from util import Queue
    fringe = Queue()                        # Fringe to manage which states to expand
    fringe.push(problem.getStartState())
    visited = []                            # List to check whether state has already been visited
    tempPath=[]                             # Temp variable to get intermediate paths
    path=[]                                 # List to store final sequence of directions 
    pathToCurrent=Queue()                   # Queue to store direction to children (currState and pathToCurrent go hand in hand)
    currState = fringe.pop()
    while not problem.isGoalState(currState):
        if currState not in visited:
            visited.append(currState)    
            successors = problem.getSuccessors(currState)
            for child,direction,cost in successors:
                fringe.push(child)
                tempPath = path + [direction]
                pathToCurrent.push(tempPath)
        currState = fringe.pop()
        path = pathToCurrent.pop()
        
    return path
Пример #57
0
def breadth_first_traverse(root):
    """breadth-first traversal or "level order traversal"

    algorithm:
      queue.
    """
    if not root:
        return

    q = Queue([root], debug=True)
    while q:
        p = q.pop(0)
        yield p
        if p.left: q.append(p.left)
        if p.right: q.append(p.right)
Пример #58
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 []
Пример #59
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()
Пример #60
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