Exemple #1
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"

    from util import Queue
    main_queue = util.Queue()
    main_queue.push(problem.getStartState())
    visited = []
    temp = []
    path = []
    main_path = Queue()
    current_state = main_queue.pop()
    while not problem.isGoalState(current_state):
        if current_state not in visited:
            visited.append(current_state)
            successors = problem.getSuccessors(current_state)
            for child, direction, cost in successors:
                main_queue.push(child)
                temp = path + [direction]
                main_path.push(temp)
        current_state = main_queue.pop()
        path = main_path.pop()

    return path

    util.raiseNotDefined()
Exemple #2
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
Exemple #3
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    closed_set = set([])
    from util import Queue
    fringes = Queue()
    state = problem.getStartState()
    node = (state, None)
    temp_fringe = [node]
    fringes.push(temp_fringe)
    while not fringes.isEmpty():
        fringe = fringes.pop()
        state = fringe[-1][0]
        if problem.isGoalState(state):
            actions = []
            for node in fringe[1:]:
                actions.append(node[1])
            return actions
        if state not in closed_set:
            closed_set.add(state)
            successors = problem.getSuccessors(state)
            for successor in successors:
                if successor[0] in closed_set:
                    continue
                node = (successor[0], successor[1])
                temp_fringe = fringe.copy()
                temp_fringe.append(node)
                fringes.push(temp_fringe)
    # print('Not found!')
    return []
Exemple #4
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
Exemple #5
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    #Queue to hold the node along with the path taken from the start node to reach that node
    queue = Queue()
    #Set to hold the node explored.
    explorednode = set()
    # Get the start node.
    startnode = problem.getStartState()
    # Push the starting node on the Queue along with an empty set to know the direction in order to reach the node.
    queue.push((startnode, []))

    # Loop till the queue is empty
    while queue.isEmpty() is not True:
        # Pop the currentnode and the direction from the queue
        currentnode, direction = queue.pop()
        # Check if the currentnode is not in explorednode.
        if currentnode not in explorednode:
            # We will now add the node to set of explored node.
            explorednode.add(currentnode)
            # If the node is the goal. We made it!!
            if problem.isGoalState(currentnode):
                # The direction holds the way to reach till the goal from the start node.
                return direction
            # Loop for each successor(child) of the current node.
            for (successor, action,
                 stepCost) in problem.getSuccessors(currentnode):
                # If the successor(child) is not explored
                if successor not in explorednode:
                    # Add the successor to the queue along with the path to reach it.
                    queue.push((successor, direction + [action]))

    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)
Exemple #7
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

    initialState = problem.getStartState()
    actionList = []
    closed = set()
    fringe = Queue()
    fringe.push((initialState, actionList))
    while fringe.isEmpty() == False:
        node = fringe.pop()
        state = node[0]
        action = node[1]

        if problem.isGoalState(state) == True:
            return action
        if state not in closed:
            closed.add(state)
            children = problem.getSuccessors(state)
            for child in children:
                newActionList = action[:]
                newActionList.append(child[1])
                fringe.push((child[0], newActionList))
    return
Exemple #8
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()
Exemple #9
0
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    """
    "*** YOUR CODE HERE ***"
    from util import Queue

    q = Queue()
    visited = []
    if (problem.getStartState()):
        q.push((problem.getStartState(), []))
    else:
        return "error"
    while not q.isEmpty():
        cur, res = q.pop()
        if (problem.isGoalState(cur)):
            return res
        if (cur not in visited):
            visited.append(cur)
            tmp = problem.getSuccessors(cur)
            for x in tmp:
                "res.append(x[1])"
                q.push((x[0], res + [x[1]]))
    return 0
    util.raiseNotDefined()
Exemple #10
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    sequence = Queue()
    #adding the start node as a list of tuple
    #(state,action,cost) to the queue for convenient retrieval
    sequence.push([(problem.getStartState(), 'None', 0)])
    # a dictionary storing seen states and the min cost to that stage
    seen = {
        problem.getStartState(): 0
    }

    while not sequence.isEmpty():

        cur_route = sequence.pop()
        # Here I retrieve the current state (x,y) from the state tuple in form (state,action,cost)
        cur_state = cur_route[-1][0]

        if cost(cur_route) <= seen[cur_state]:

            if problem.isGoalState(cur_state):
                return retrieve_direction(cur_route)

            for successor in problem.getSuccessors(cur_state):
                new_state = cur_route + [successor]
                # Path check to eliminate and state that has been visited
                if not successor[0] in seen or cost(new_state) < seen[
                        successor[0]]:
                    sequence.push(new_state)
                    seen[successor[0]] = cost(new_state)
    return False  #return False upon no solution found
Exemple #11
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()
Exemple #12
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]))
Exemple #13
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]]))
Exemple #14
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
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
Exemple #16
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)
Exemple #17
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)
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 ***"
    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 []
Exemple #20
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
Exemple #21
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from game import Directions
    from util import Queue

    #exploredSet = set()
    exploredSet = []
    frontier = Queue()
    frontier.push((problem.getStartState(), []))
    ourPath = []
    while 1:
        if frontier.isEmpty():
            return []

        currNode = frontier.pop()
        ourPath = currNode[1]
        exploredSet.append(currNode[0])
        if problem.isGoalState(currNode[0]):
            return ourPath

        for i in problem.getSuccessors(currNode[0]):
            if i[0] not in exploredSet and i[0] not in [
                    row[0] for row in frontier.list
            ]:
                frontier.push((i[0], ourPath + [i[1]]))

    util.raiseNotDefined()
Exemple #22
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
Exemple #23
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)
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()
Exemple #25
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))
Exemple #26
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 []
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 []
Exemple #28
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):
Exemple #29
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 []
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
Exemple #31
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
Exemple #32
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()
Exemple #33
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    startState = problem.getStartState()
    visited = []

    from util import Queue
    queue = Queue()

    queue.push((startState, []))

    while (not queue.isEmpty()):
        #pdb.set_trace()
        topOfQueue, action = queue.pop()
        visited.append(topOfQueue)

        if (problem.isGoalState(topOfQueue)):
            return action

        for succesor in problem.getSuccessors(topOfQueue):
            if (succesor[0] not in visited):
                queue.push((succesor[0], action + [succesor[1]]))
                visited.append(succesor[0])

    util.raiseNotDefined()
Exemple #34
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")
Exemple #35
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    queue = Queue()
    actions=[]
    visited=[]
    start_pos=problem.getStartState()
    queue.push( (start_pos, actions) )
    while not queue.isEmpty():
        top_item = queue.pop()
        position_list = top_item[0]
        actions_list = top_item[1]

        if problem.isGoalState(position_list):
            return actions_list
        if position_list not in visited:
            visited.append(position_list)
            successor_nodes=problem.getSuccessors(position_list)
            for nodes in successor_nodes:
                succ_node=nodes[0]
                succ_action=nodes[1]
                if succ_node not in visited:
                    nxt_action=actions_list+[succ_action]
                    queue.push((succ_node,nxt_action))
Exemple #36
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))
Exemple #37
0
 def deadRoadsWithDepth(self):
     from util import Queue
     deadEntry, deadRoads = self.deadRoads()
     withDepth = {}
     done = []
     for i in deadEntry:
         explored = Queue()
         depth = 0
         withDepth[i] = depth
         explored.push(i)
         done.append(i)
         while not explored.isEmpty():
             j = explored.pop()
             (x, y) = j
             adjacentPoints = self.adjacentValidPoints(x, y)
             adjacentPoints = [
                 j for j in adjacentPoints
                 if j in deadRoads and j not in done and j not in deadEntry
             ]
             if len(adjacentPoints) != 0:
                 depth += 1
             for k in adjacentPoints:
                 explored.push(k)
                 done.append(k)
                 withDepth[k] = depth
     return withDepth
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  
Exemple #39
0
def breadthFirstSearch(problem):
    "Search the node of least total cost first. "
    "*** YOUR CODE HERE ***"

    start_state = problem.getStartState()
    frontier = Queue()  # queue for frontier
    explored = set()
    frontier.push((start_state, []))
    # [] -> path required to reach here
    # 0 step cost to reach here
    # heuristic(start_state, problem) estimated heurisic distance to reach goal

    while not frontier.isEmpty():
        location, path_to_reach_here = frontier.pop()
        explored.add(location)
        if problem.isGoalState(location):
            return path_to_reach_here
        for neighbor in problem.getSuccessors(location):
            neighbor_location, neighbor_action, neighbor_step_cost = neighbor
            frontier_list = [
                element[0] for element in frontier.list
            ]  # get a list of all elements in frontier s.union(t)
            frontier_union_explored = list(set(frontier_list).union(explored))
            if neighbor_location not in frontier_union_explored:
                path_till_neighbor = path_to_reach_here + [neighbor_action]
                # print neighbor_location, path_till_neighbor
                frontier.push((neighbor_location, path_till_neighbor))
Exemple #40
0
 def get_impasse(self, successor, current_position, depth, foods_capsules):
     is_there_food = False
     bfs_queue = Queue()
     bfs_queue.push(successor)
     already_seen = set()
     already_seen.add(current_position)
     for i in range(1, depth):
         if not bfs_queue.isEmpty():
             successor = bfs_queue.pop()
             successor_pos = successor.getAgentPosition(self.index)
             if successor_pos in foods_capsules:
                 is_there_food = True
             already_seen.add(successor_pos)
             legal_actions = successor.getLegalActions(self.index)
         else:
             break
         for action in legal_actions:
             if action != Directions.STOP:
                 temp_successor = self.getSuccessor(successor, action)
                 successor_pos = temp_successor.getAgentPosition(self.index)
                 if successor_pos not in already_seen:
                     bfs_queue.push(temp_successor)
     if bfs_queue.isEmpty():
         return len(already_seen), is_there_food
     else:
         return False, is_there_food
Exemple #41
0
 def choose_flee_action(self, game_state):
   #
   q = Queue()
   q.push((game_state, []))
   visited = []
   i = 0
   while not q.is_empty():
     i = i+1
     state, route = q.pop()
     if self.nearest_ghost_distance(state) <= 1 and state != game_state:
       continue
     elif state.get_agent_position(self.index) in visited:
       continue
     elif self.in_home_territory(state,state.get_agent_position(self.index),0):
       if len(route) == 0:
         return Directions.STOP
       else:
         return route[0]
     visited = visited + [state.get_agent_position(self.index)]
     actions = state.get_legal_actions(self.index)
     rev = Directions.REVERSE[state.get_agent_state(self.index).configuration.direction]
     if rev in actions and len(actions) > 1 and i!=1:
       actions.remove(rev)
     for action in actions:
       q.push((self.get_successor(state,action),route+[action]))
   return random.choice(game_state.get_legal_actions(self.index))
Exemple #42
0
 def get_actions_to_destination(self, proper_output_gate, cur_state):
     queue = Queue()
     queue.push(cur_state)
     visited = set()
     child_to_parent = {cur_state: (None, None)}
     while not queue.isEmpty():
         node = queue.pop()
         node_pos = node.getAgentPosition(self.index)
         if node_pos == proper_output_gate:
             actions = []
             while child_to_parent[node][0] is not None:
                 (node, action) = child_to_parent[node]
                 actions.append(action)
             actions.reverse()
             return actions
         visited.add(node_pos)
         legal_actions = node.getLegalActions(self.index)
         for action in legal_actions:
             if action != Directions.STOP:
                 temp_successor = self.getSuccessor(node, action)
                 successor_pos = temp_successor.getAgentPosition(self.index)
                 if successor_pos not in visited and self.is_agent_in_base(
                         successor_pos):
                     queue.push(temp_successor)
                     child_to_parent[temp_successor] = (node, action)
Exemple #43
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
Exemple #44
0
    def BFS(self, gameState):
        from util import Queue
        visited, movements = [], {}
        startAgentState = gameState.getAgentState(self.index)
        startLoc = startAgentState.getPosition()

        movements[startLoc] = []
        visited.append(startLoc)

        queue = Queue()
        queue.push(gameState)

        while not queue.isEmpty():
            currGameState = queue.pop()
            currLoc = currGameState.getAgentState(self.index).getPosition()

            if self.isGoal(currGameState):
                return currLoc, movements[currLoc][:-1]

            actions = currGameState.getLegalActions(self.index)

            for action in actions:
                succGameState = self.getSuccessor(currGameState, action)
                succLoc = succGameState.getAgentState(self.index).getPosition()

                if succLoc not in visited:
                    visited.append(succLoc)
                    movements[succLoc] = []
                    pre = movements[currLoc][:]
                    pre.append(action)
                    movements[succLoc].extend(pre)
                    queue.push(succGameState)
Exemple #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()
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
Exemple #47
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()
Exemple #48
0
def breadthFirstSearch(problem):
    from util import Queue

    stackState = Queue()
    visit = []
    add = []
    path = []
    if problem.isGoalState(problem.getStartState()):
        return []
    stackState.push(
        (problem.getStartState(), [])
    )  #luu duong di den diem hien tai va node problem.getStartState() tra ve (x,y)

    while (True):
        if stackState.isEmpty():
            return []  #k tim dc duong

        currentt, path = stackState.pop()  #lay node tiep theo

        visit.append(currentt)  # them vao visited
        if (problem.isGoalState(currentt)):  #neu la dich thi tra ve path
            return path
        successorr = problem.getSuccessors(
            currentt)  #laymang cac nut xung quanh
        if successorr:
            for node in successorr:  #node ((x,y),[...])
                if node[0] not in visit and node[0] not in add:
                    pathnode = path + [node[1]]
                    stackState.push((node[0], pathnode))
                    add.append(node[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 []
Exemple #50
0
def breadthFirstSearchCountLimited(problem, limit=3):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    # count = 0
    goals = []
    closed_set = set([])
    from util import Queue
    fringes = Queue()
    state = problem.getStartState()
    node = state
    temp_fringe = [node]
    fringes.push(temp_fringe)
    while not fringes.isEmpty():
        fringe = fringes.pop()
        state = fringe[-1]
        if state not in closed_set:
            closed_set.add(state)
            if problem.isGoalState(state):
                goals.append(state)
            successors = problem.getSuccessors(state)
            for successor in successors:
                if successor[0] in closed_set:
                    continue
                node = successor[0]
                temp_fringe = fringe.copy()
                temp_fringe.append(node)
                if len(temp_fringe) > limit:
                    continue
                fringes.push(temp_fringe)
    return goals
Exemple #51
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]
Exemple #52
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()
Exemple #53
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 []
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
Exemple #56
0
def breadthFirstSearch(graph):
    state = 0
    nodes = Queue()
    usedstates = set()
    node = [state, [state]]
    nodes.push(node)
    while not nodes.isEmpty():
        node = nodes.pop()
        [s, actions] = node
        if not s in usedstates:
            usedstates.add(s)
            if graph.isGoalState(s):
                return node[1]
            for ns in graph.getSuccessors(s):
                new_actions = actions + [ns]
                nodes.push([ns, new_actions])
    return None
Exemple #57
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    from util import Queue
    start = problem.getStartState()
    checkQueue = Queue()
    checkQueue.push((start,[]))
    visitedStates = []
    while not checkQueue.isEmpty():
        popState,popDirection= checkQueue.pop()
        for successors in problem.getSuccessors(popState):
            state,direction,cost = successors
            if not state in visitedStates:
                if problem.isGoalState(state):
                    return popDirection + [direction]
                checkQueue.push((state, popDirection +[direction]))
                visitedStates.append(state)
    return []
Exemple #58
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    frontier=Queue()
    start_node = Node(problem.getStartState(), step_cost=0)
    explored = []
    frontier.push(start_node)
    while not frontier.isEmpty():
        node = frontier.pop()
        explored.append(node.state)
        if problem.isGoalState(node.state):
            return node.getPath()
        for child in node.getChildren(problem):
            h = isStateInList(frontier.list,child.state)
            if not child.state in explored and h == -1:
                frontier.push(child)
Exemple #59
0
def breadthFirstSearch(problem):
    "Search the shallowest nodes in the search tree first. [p 81]"
    "*** YOUR CODE HERE ***"
    """
    Implements BFS by traversing the graph in "level-order" using a Queue,
    returning a path to the goal if one exists.
    """
    from util import Queue

    # Constants for readability
    STATE = 0
    DIRECTION = 1

    # A list containing the states already encountered
    nodeHistory = []
    # A list used to store the nodes to explore
    nodeQueue = Queue()

    # Start by enqueueing the start, along with an empty path
    nodeQueue.push(((problem.getStartState(), 'Stop', 0), []))

    # Iterate through the queue
    while not nodeQueue.isEmpty():
        # Get the parent node, and the path to it
        node, path = nodeQueue.pop()
        # Seperate the parent state for successor query
        parent = node[STATE]
        # For each child of the parent state,
        for i, child in enumerate(problem.getSuccessors(parent)):
            # Check to see if the child has been explored
            if not child[STATE] in nodeHistory:
                # If no,
                # Check to see if the goal state has been reached
                if problem.isGoalState(child[STATE]):
                    path = path + [child[DIRECTION]]
                    return path
                # Otherwise,
                else:
                    # Mark the node as explored
                    nodeQueue.push((child, path + [child[DIRECTION]]))
                    # And enqueue the child
                    nodeHistory.append(child[STATE])

    # Return an empty list if no path can be found
    return []