コード例 #1
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

  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)
コード例 #2
0
ファイル: search.py プロジェクト: naplr/pacman_sp14
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")
コード例 #3
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
コード例 #4
0
ファイル: search.py プロジェクト: belled10468/AI1.88Project1
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)
コード例 #5
0
ファイル: search.py プロジェクト: prasidh09/Pacman_Projects
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):
コード例 #6
0
ファイル: search.py プロジェクト: znyupup/Pacman
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))
コード例 #7
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
コード例 #8
0
ファイル: search.py プロジェクト: TrungMDang/TCSS435
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
コード例 #9
0
ファイル: search.py プロジェクト: Jornason/Class-Projects
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]))
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 []
コード例 #11
0
ファイル: search.py プロジェクト: szmark001/CS-188
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))
コード例 #12
0
ファイル: search.py プロジェクト: azimmomin/Search_Pacman
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
コード例 #13
0
ファイル: search.py プロジェクト: erikm0111/AIclass
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)
コード例 #14
0
ファイル: search.py プロジェクト: dowd83/Pacman-Search
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()
コード例 #15
0
ファイル: search.py プロジェクト: gutiere/search
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()
コード例 #16
0
ファイル: search.py プロジェクト: hermetico/IA
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]
コード例 #17
0
ファイル: search.py プロジェクト: rmhasan/pacman
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 []
コード例 #18
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
コード例 #19
0
ファイル: search.py プロジェクト: bottleling/pacmansearch
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)
コード例 #20
0
ファイル: search.py プロジェクト: simjega/flownetwork
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
コード例 #21
0
ファイル: search.py プロジェクト: sindhuula/Sem2
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 []
コード例 #22
0
ファイル: search.py プロジェクト: kli66/UWMadison
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    if problem.isGoalState(problem.getStartState()):
        return list()


    ##initialize the list of actions to return, frontier and explored set
    frontier = Queue()
    listOfActions = list()

    ##frontier includes the state and the list of actions to get to that state to construct the node
    frontier.push( [problem.getStartState(),listOfActions] )
    explored = list()

    ##keep a list of frontier states to check if a state is in the frontier
    frontierState =  list()

    ##looping while the frontier is not empty
    while not(frontier.isEmpty()):

        ##pop one node off the frontier, check if it is the goal state
        node = frontier.pop()
        if problem.isGoalState(node[0]):
            return node[1]

        ##add the state to the explored set if it is not the goal state
        explored.append(node[0])

        ##looping through current state's successor states
        for state,action,stepCost in problem.getSuccessors(node[0]):

            oldActions = list(node[1])

            ##add the action needed from current state to next state onto the action list
            oldActions.append(action)
            nextNode = [state, oldActions]

            ##add the state to the frontier if it is both unexplored and not on the frontier
            if(state not in explored and state not in frontierState):
                frontier.push(nextNode)
                frontierState.append(state)

    return None
コード例 #23
0
def breadthFirstSearch(problem):
  """
  Search the shallowest nodes in the search tree first.
  [2nd Edition: p 73, 3rd Edition: p 82]
  """
  "*** YOUR CODE HERE ***"
  from game import Directions
  from util import Queue
  Explored = {}
  Frontier = Queue()
  
  node = 0
  current = problem.getStartState()
  #print "bfs first state", current
  Explored[current] = 1
  succ = problem.getSuccessors(current)
  for k in succ:
    #print "initial push",k
    Frontier.push([k]);

  while not (Frontier.isEmpty()):
      current = Frontier.pop()
      node = current[-1][0]
      #print "curr path and node",current,node,"explored status",(node in Explored),"\n"
      # check if done
      if (problem.isGoalState(node)):
          break
      #print node
      if(node in Explored):
          continue
      Explored[node] = 1;
      succ = problem.getSuccessors(node)
      for k in succ:
          if not (k[0] in Explored):
              #if not (Frontier.isPresent(current + [k])):
                Frontier.push(current + [k]);
                #Explored[k[0]] = 1;
 
  sol = []
  for k in current:
    sol += [k[1]]

  #print current
  #print "action sol", sol
  return  sol
コード例 #24
0
ファイル: search.py プロジェクト: MartinKilonzo/School-Work
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 []
コード例 #25
0
ファイル: multiAgents.py プロジェクト: rwwaskk/CS188-Berkeley
def mazeDistance(x, y, walls):
	from util import Queue
 
	queue = Queue()
	visitedSet = set()
	queue.push((x, 0))
  
	while not queue.isEmpty():
		currentNode = queue.pop()
		if(currentNode[0] == y):
			return currentNode[1]
		successors = getSuccessors(currentNode[0], walls)
		for successor in successors:
			if successor not in visitedSet:
				queue.push((successor, currentNode[1] + 1))
				visitedSet.add(successor)
      
	return None
コード例 #26
0
ファイル: search.py プロジェクト: RPing/Pacman-Agent
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "[Project 2] YOUR CODE HERE"
    #util.raiseNotDefined()
    from util import Queue
    from game import Directions
    solution = []          #direction
    to_visit = Queue()     #position
    visited = set()        #already visit
    cost = {}              #cost of every visited point
    cost[problem.getStartState()] = 0
    to_visit.push(problem.getStartState())
    #visited.add(problem.getStartState())
    startPoint = problem.getStartState()
    while not to_visit.isEmpty():
        v = to_visit.pop()
        visited.add(v)
        if problem.isGoalState(v):
            while v != startPoint:
                minimum = 99999
                temp = problem.getSuccessors(v)[0]
                for x in problem.getSuccessors(v):
                    if x[0] in visited and cost[x[0]] < minimum:
                        minimum = cost[x[0]]
                        temp = x
                v = temp[0]
                
                if temp[1] == Directions.EAST:
                    solution.append(Directions.WEST)
                elif temp[1] == Directions.WEST:
                    solution.append(Directions.EAST)
                elif temp[1] == Directions.NORTH:
                    solution.append(Directions.SOUTH)
                else:
                    solution.append(Directions.NORTH)
            solution.reverse()
            #print solution
            return solution
        else:
            for x in problem.getSuccessors(v):
                if x[0] not in visited:
                    to_visit.push(x[0])
                if x[0] not in cost:
                    cost[x[0]] = cost[v] + x[2]
コード例 #27
0
ファイル: search.py プロジェクト: robertsmieja/CS4341-AI
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
コード例 #28
0
ファイル: search.py プロジェクト: Nirvana-icy/pacman
def breadthFirstSearch(problem):
  """
  Search the shallowest nodes in the search tree first.
  [2nd Edition: p 73, 3rd Edition: p 82]
  """
  "*** YOUR CODE HERE ***"
  from game import Directions
  s = Directions.SOUTH
  w = Directions.WEST
  n = Directions.NORTH
  e = Directions.EAST
  start = problem.getStartState()
  print "the start state is ", start
  if problem.isGoalState(start):
    return []
  from util import Queue
  statesQueue = Queue()
  statesQueue.push((start,[]))
  print "start is ", start
  exploredSet = set([start])
  while not statesQueue.isEmpty():
    tup1 = statesQueue.pop()
    state = tup1[0]
    path = tup1[1]
    if problem.isGoalState(state):
      return path
    successors = problem.getSuccessors(state)
    for succ in successors:
      succState = succ[0]
      move = succ[1]
      #cost = succ[2]
      tempPath = list(path)
      if not succState in exploredSet:
        exploredSet.add(succState)
        if move == 'North':
          tempPath.append(n)
        elif move == 'East':
          tempPath.append(e)
        elif move == 'South':
          tempPath.append(s)
        elif move == 'West':
          tempPath.append(w)
        statesQueue.push((succState,tempPath))        
  return []
コード例 #29
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue

    queue = Queue()  # (state, path)
    visit = set()
    state = problem.getStartState()
    queue.push((state, []))

    while not queue.isEmpty():
        state, path = queue.pop()
        visit.add(state)
        if problem.isGoalState(state):
            return path
        for nextState, direction, score in problem.getSuccessors(state):
            if nextState not in visit:
                queue.push((nextState, path + [direction]))
                visit.add(nextState)
コード例 #30
0
def breadthFirstSearch(problem):
    from util import Queue
    closedSet = set() # set of nodes already visited
    fringe    = Queue() # queue that contains the fringe of the search
    path      = [] # list holding the path that will be returned for PacMan to follow
    
    # push the start state to the fringe
    state = problem.getStartState() 
    node  = makeNode(state) 
    fringe.push(node) 
    
    # step through the fringe until it is empty
    while not fringe.isEmpty():
        # update the information about the current node and add it to the set
        node  = fringe.pop()
        state = node.state
        path  = node.path
        closedSet.add(state)

        # return the path if you reach the goal
        if problem.isGoalState(state):
            return path
            
        # add the node's successors to the fringe, start with the first successor
        # and expand all succesors before pursuing further nodes
        successors = problem.getSuccessors(state)
        for each in successors:
            # get information from the successor
            nextState, nextAction, cost = each
            if nextState not in closedSet:    
                closedSet.add(nextState)
                # update the path to include the successor
                nextPath  = []
                for every in path:
                    nextPath.append(every)
                nextPath.append(nextAction)
                # build a new node with the new successor's information and add it to the fringe
                nextNode = makeNode(nextState, nextPath)
                fringe.push(nextNode)
 
    # if we reach this point - there was no solution
    print "Breadth First Search was unable to find a solution."
    return None
コード例 #31
0
def breadthFirstSearch(problem):
    """
    Q1.2
    Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    """The code is same as Depth First search, but we use Queue instead of Stack """
    if problem.isGoalState(problem.getStartState()):
        return []
    """As we need FIFO for DFS"""
    from util import Queue
    """"Now I have to initialize frontier with the initial state of the problem, according to fig 3.7"""
    Frontier = Queue()
    """Now I push the valid start state"""
    Frontier.push((problem.getStartState(), []))
    """initializing empty explored set"""
    statePath = []
    stateVisited = []
    while (True):
        """return failure if Frontier is empty """
        if Frontier.isEmpty():
            return []
        """choose a leaf node and remove it from Frontier"""
        xy, statePath = Frontier.pop()
        """ if it is the goal state, return it"""
        if problem.isGoalState(xy):
            return statePath
        """Add the node to the explored set"""
        stateVisited.append(xy)
        """expand the chosen node """
        succecorPath = problem.getSuccessors(xy)
        """print ( problem.getSuccessors(xy)), test for successor """
        if succecorPath:
            for paths in succecorPath:
                """Adding resulting nodes in Frontier only if not in frontier or explored set """
                if paths[0] not in stateVisited and paths[0] not in (
                        state[0] for state in Frontier.list):
                    """A condtion is added in the above if, we had to check all the nodes where we have been (states) """
                    newPath = statePath + [paths[1]]
                    """
                    print(paths[0])
                    print(paths[1])
                    print(newPath) """
                    Frontier.push((paths[0], newPath))
コード例 #32
0
def coinGroup(xy, gameStateData):
    food = gameStateData.getFood().asList()
    capsules = gameStateData.getCapsules()
    q = Queue()
    q.push(xy)
    seen = set()
    seen.add(xy)
    seenCoin = set()
    seenCoin.add(xy)
    while not q.isEmpty():
        nextPoint = q.pop()
        neighbors = game.Actions.getLegalNeighbors(nextPoint, gameStateData.getWalls())
        for neighbor in neighbors:
            if neighbor not in seen:
                seen.add(neighbor)
                if neighbor in food or neighbor in capsules:
                    seenCoin.add(neighbor)
                    q.push(neighbor)
    return seenCoin
コード例 #33
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"

    closed = []
    from util import Queue
    fringe = Queue()
    fringe.push((problem.getStartState(), [], 1))

    result = []
    "print type(fringe)"
    while (fringe.isEmpty() == False):
        node = fringe.pop()
        """
        print
        print node
        """
        result = node[1]

        if node[0] not in closed:
            """
            print "Inloop",node[0]
            
            print type(node[1])
            print result
            print node[1]
            
            print result
            """
            if problem.isGoalState(node[0]):
                "print result"
                return result
            closed.append(node[0])

            temp = problem.getSuccessors(node[0])

            #print temp
            for child_node in temp:
                fringe.push((child_node[0], result + [child_node[1]], 1))

    return []

    util.raiseNotDefined()
コード例 #34
0
ファイル: search.py プロジェクト: tranhieu956230/pacman-cs188
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    parentMaps = {}
    visitedNodes = []
    searchStates = Queue()
    searchStates.push((problem.getStartState(), ""))
    while not searchStates.isEmpty():
        top = searchStates.pop()
        if not top[0] in visitedNodes:
            visitedNodes.append(top[0])
            if problem.isGoalState(top[0]):
                return tracePath(parentMaps, top)
            successors = problem.getSuccessors(top[0])
            parentMaps[top] = successors
            for successor in successors:
                if not successor[0] in visitedNodes:
                    searchStates.push(successor)
    return [Directions.STOP]
コード例 #35
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    closed = []
    fringe = Queue()
    fringe.push((problem.getStartState(), []))

    while not fringe.isEmpty():
        (node, address) = fringe.pop()

        if (not node in closed):
            closed.append(node)

            if problem.isGoalState(node):
                return address

            for child, child_address, cost in problem.getSuccessors(node):
                fringe.push((child, address + [child_address]))
コード例 #36
0
ファイル: snake_problem.py プロジェクト: roey89/snake
def check_goal_state(problem):
    fringe = Queue()
    been_there = []
    fringe.push((problem.get_start_state(), []))
    for i in range(snake_to_check_depth(len(problem.state.snake))):
        if fringe.isEmpty():
            return False
        current_board, actions = fringe.pop()
        if illegal(current_board.snake[0], current_board.board_size,
                   current_board.snake[1:]):
            pass
        if current_board not in been_there:
            successors = problem.get_successors(current_board)
            for item in successors:
                temp_lst = actions[:]
                temp_lst.append(item[1])
                fringe.push((item[0], temp_lst))
            been_there.append(current_board)
    return True
コード例 #37
0
ファイル: search.py プロジェクト: jd2695/Pacman
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    """
    "*** YOUR CODE HERE ***"
    from game import Directions

    s = Directions.SOUTH
    w = Directions.WEST
    n = Directions.NORTH
    e = Directions.EAST
    start = problem.getStartState()
    if problem.isGoalState(start):
        return []
    from util import Queue

    statesQueue = Queue()
    exploredSet = set([start])
    tup = (start, [])
    statesQueue.push(tup)
    while not statesQueue.isEmpty():
        tup1 = statesQueue.pop()
        state = tup1[0]
        path = tup1[1]
        if problem.isGoalState(state):
            return path
        successors = problem.getSuccessors(state)
        for succ in successors:
            coor = succ[0]
            move = succ[1]
            tempPath = list(path)
            if not coor in exploredSet:
                exploredSet.add(coor)
                if move == "North":
                    tempPath.append(n)
                elif move == "East":
                    tempPath.append(e)
                elif move == "South":
                    tempPath.append(s)
                elif move == "West":
                    tempPath.append(w)
                statesQueue.push((coor, tempPath))
    return []  # nodes expanded, tiny=15, medium=269, big=620
コード例 #38
0
ファイル: search.py プロジェクト: Rijul25/Project---Search
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from game import Directions
    from util import Queue
    s = Directions.SOUTH
    w = Directions.WEST
    e = Directions.EAST
    n = Directions.NORTH

    visited = [None]  # list of states (each state is a position in this case)
    queue = Queue(
    )  # contains pairs. each pair's first elem is a list of actions. second elem is state
    queue.push([[], problem.getStartState()])

    while (not queue.isEmpty()):
        top = queue.pop()  # this is the top of the stack
        #print("@@@@@TOP: ", top)
        actions = top[0]
        state = top[1]
        #print("@@@@@@STATE: ", state)

        # print("@@@@@@ENTERETED LOOP")
        if problem.isGoalState(state):
            #   print("@@@@ACTIONS: ", actions)
            return actions

        visited.append(state)

        for child in problem.getSuccessors(
                state):  #returns (nextstate, actions, cost)
            childAction = child[1]
            childState = child[0]
            if (childState not in visited):
                visited.append(childState)
                # print ("@@@@@@STATE: ", child)
                #if (child[0] not in visited):
                tempActions = actions[:]
                # print("!!!!!!!TYPE ", type(tempActions))
                tempActions.append(childAction)
                queue.push([tempActions, child[0]])
    return None
    util.raiseNotDefined()
コード例 #39
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    startState = problem.getStartState()
    queue = Queue()
    visited = {startState}
    action = []
    queue.push((startState, action))
    while not queue.isEmpty():
        v = queue.pop()
        visited.add(v[0])
        if problem.isGoalState(v[0]):
            return v[1]
        # queue.pop(len(queue) - 1)
        successors = problem.getSuccessors(v[0])
        for successor in successors:
            if successor[0] not in visited:
                queue.push((successor[0], v[1] + [successor[1]]))

    return []

    # startState = problem.getStartState()
    #
    # queue = Queue()
    # visited = set()
    # visited.add(startState[0])
    # action = []
    # queue.push((startState, action))
    # while not queue.isEmpty():
    #     v = queue.pop()
    #     print v
    #     visited.add(v[0])
    #     if problem.isGoalState(v[0]):
    #         print v[1]
    #         return v[1]
    #     successors = problem.getSuccessors(v[0])
    #     for successor in successors:
    #         if successor[0] not in visited:
    #             queue.push((successor[0], v[1] + [successor[1]]))
    #
    # return []
    util.raiseNotDefined()
コード例 #40
0
ファイル: search.py プロジェクト: JehleYu/Pac-man-game
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    Wantvisit = Queue()
    visited = set()
    Wantvisit.push((problem.getStartState(), [], 0))
    while not Wantvisit.isEmpty():
        node = Wantvisit.pop()
        if node[0] in visited:
            continue
        visited.add(node[0])
        if problem.isGoalState(node[0]): return node[1]
        for nodelocation, nodepath, nodecost in problem.getSuccessors(node[0]):
            way = node[1] + [nodepath]
            cost = node[2] + nodecost
            Wantvisit.push((nodelocation, way, cost))
    return []
    util.raiseNotDefined()
コード例 #41
0
ファイル: search.py プロジェクト: virajp691/CMPS-140
def breadthFirstSearch(problem):
    "Search the shallowest nodes in the search tree first. [p 81]"
    from util import Queue
    fringe = Queue()
    visited = []
    final_path = []
    fringe.push((problem.startingState(), [], 1))

    while not fringe.isEmpty():
        state, nodepath, cost = fringe.pop()
        if problem.isGoal(state):
            final_path = nodepath
            print "Found Goal"
            break
        for successor in problem.successorStates(state):
            if successor[0] not in visited:
                visited.append(successor[0])
                fringe.push((successor[0], nodepath + [successor[1]], cost))
    return final_path
コード例 #42
0
ファイル: search.py プロジェクト: Snedakerwalker1/cs188
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    from util import Queue
    start = problem.getStartState()
    closed = []
    fringe = Queue()
    tup = (start, [])
    fringe.push(tup)
    while not fringe.isEmpty():
        spot, path = fringe.pop()
        if problem.isGoalState(spot):
            return path
        if not spot in closed:
            closed += [spot]
            for successor in problem.getSuccessors(spot):
                nspot, direction, val = successor
                ntup = (nspot, path + [direction])
                fringe.push(ntup)
    return "No Path Found"
コード例 #43
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    import copy

    openList = Queue()
    closedList = []
    pathToNode = []

    # get the first node of the graph
    openList.push(((problem.getStartState(), "-", 0), pathToNode))

    while not openList.isEmpty():
        pathToNode = []
        #print "Open list: ",openList.list
        #print "Closed List: ", closedList
        currentNode, pathToNode = openList.pop()
        pathToNode.append(currentNode[1])
        closedList.append(currentNode[0])
        #print "Current: ",currentNode
        #print "Path:",pathToNode

        # goal state
        if problem.isGoalState(currentNode[0]):
            pathToNode.append(currentNode[1])
            # load the actions and return

            #print "Path to goal:",pathToNode[1:]
            return pathToNode[1:]

        for node in problem.getSuccessors(currentNode[0]):
            if node[0] not in closedList:
                #print "Children node:",node
                if problem.isGoalState(node[0]):
                    pathToNode.append(node[1])
                    #print "Path to goal:",pathToNode[1:]
                    print "Total steps:", len(pathToNode[1:])
                    return pathToNode[1:]
                #print "Path",pathToNode
                openList.push((node, copy.copy(pathToNode)))

    util.raiseNotDefined()
コード例 #44
0
ファイル: search.py プロジェクト: AnthonyGuerra7/PacManAI
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue
    #This is a queue which contain the position that the pacman will travel
    PositionQueue = Queue()
    #This will contain all of the visited states
    Visited = []  
    #This will contain the path from the starting state
    Path = []
    #Test to see if the inital state is the goal state which you are intending to find.
    if problem.isGoalState(problem.getStartState()):
        return []

    #This will start to push onto the queue from the beginning and will find a solution. The initial path is an empty list
    PositionQueue.push((problem.getStartState(),[]))

    while(True):

        #This will end the program is a solution cannot be found
        if PositionQueue.isEmpty():
            return []

        #This will gather the information of the current state (p1,p2)
        p1p2,Path = PositionQueue.pop()
        Visited.append(p1p2)

        #Check to see if new position p1p2 is the end goal
        if problem.isGoalState(p1p2):
            return Path

        #Get Possible Successors of the current state
        q1q2 = problem.getSuccessors(p1p2)

        #This will add new states in the queue
        if q1q2:
            for option in q1q2:
                if option[0] not in Visited and option[0] not in (state[0] for state in PositionQueue.list):

                    #Calculate a new path
                    NPath = Path + [option[1]]
                    PositionQueue.push((option[0],NPath))
コード例 #45
0
ファイル: search.py プロジェクト: iamsteveng/AIND-Lab-Pacman
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    [2nd Edition: p 73, 3rd Edition: p 82]
    Test case: python pacman.py -l mediumMaze -p SearchAgent -a fn=bfs
    Test case: python pacman.py -l bigMaze -p SearchAgent -a fn=bfs -z .5
    """
    from util import Queue
    import copy
    frontier = Queue()
    explored = []

    if problem.isGoalState(problem.getStartState()):
        return []
    # Kick start with the start state
    # Save the action stack (ancestor path) together with the state
    frontier.push((problem.getStartState(), []))
    explored.append(problem.getStartState())

    while True:
        if frontier.isEmpty():
            return False
        # Get the first one from the Queue to explore
        (current_state, action_stack) = frontier.pop()
        # Search for child states
        successors = problem.getSuccessors(current_state)
        for s in successors:
            (next_state, next_action, cost) = s
            # Skip visited state (frontier and explored), prevent infinite loop
            if is_visited(explored, next_state):
                continue
            # Deep copy the ancestor path and add this successor
            # so that we can return the action stack (ancestor path) whenever we found the goal state
            next_action_stack = copy.deepcopy(action_stack)
            next_action_stack.append(next_action)
            # Return action stack when found the goal state
            if problem.isGoalState(next_state):
                return next_action_stack
            # If not goal state, push the state into frontier for later exploration
            # Save the action stack (ancestor path) together with the state
            frontier.push((next_state, next_action_stack))
            explored.append(next_state)
コード例 #46
0
def breadthFirstSearch(problem):
    "Search the shallowest nodes in the search tree first. [p 81]"
    "*** YOUR CODE HERE ***"
    from game import Directions
    from util import Queue
    n = Directions.NORTH
    s = Directions.SOUTH
    e = Directions.EAST
    w = Directions.WEST
    explored = []
    frontier = Queue()
    frontierSet = []
    start_node = problem.getStartState()
    if problem.isGoalState(start_node) == True:
        return []
    frontier.push((start_node, []))
    while frontier.isEmpty() == False:
        currentNode = frontier.pop()
        currentState = currentNode[0]
        actions = currentNode[1]
        if (problem.isGoalState(currentState) == True):
            #print actions
            return actions
        explored.append(str(currentState))
        successors = problem.getSuccessors(currentState)
        for successor in successors:
            succState = successor[0]
            succAction = successor[1]
            if str(succState) not in explored and str(
                    succState) not in frontierSet:
                frontierSet.append(str(succState))
                tempPath = list(actions)
                if (succAction == 'North'):
                    tempPath.append(n)
                elif (succAction == 'East'):
                    tempPath.append(e)
                elif (succAction == 'South'):
                    tempPath.append(s)
                elif (succAction == 'West'):
                    tempPath.append(w)
                frontier.push((succState, tempPath))
    return []
コード例 #47
0
ファイル: search.py プロジェクト: dillxcl/AIPacman
def breadthFirstSearch(problem):
    """Questoin 1.2
     Search the shallowest nodes in the search tree first.
     """

    "*** YOUR CODE HERE ***"
    visited = []
    direction = []
    visited_node = []
    fringe = Queue()
    count = 0
    #StartState = ((problem.getStartState(), "" , 0))
    Startstate = problem.getStartState()
    fringe.push((Startstate, direction))
    Successor = []

    # while the queue is not empty
    while not fringe.isEmpty():

        # Get all the values from queue
        current_node, direction = fringe.pop()
        # if it reaches the goal then return direction
        if problem.isGoalState(current_node) == True:
            direction.append(Successor[1])
            return direction
        # if not reaches
        else:
            # check the current is in visited list or not
            if current_node not in visited:
                Successor = problem.getSuccessors(current_node)
                visited = visited + [current_node]

                # looping the successor to get the next node and direction
                for element in Successor:
                    # check whether the next node is in visited list or not
                    if element[0] not in visited:
                        if problem.isGoalState(element[0]) == True:
                            return direction + [element[1]]
                        else:
                            #push everything to the queque
                            fringe.push((element[0], direction + [element[1]]))
    return direction
コード例 #48
0
def breadthFirstSearch(pacmanPosition, wallPosition, goalPosition):
    from util import Queue
    queue = Queue()
    queue.push(pacmanPosition)
    visited = { pacmanPosition: (None, None) }
    solution = []
    while not queue.isEmpty() and not solution:
        node = queue.pop()
        if node in goalPosition:
            solution = computeSolution(node, visited)
        if not solution:
            for direction in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:
                x, y = node
                dx, dy = Actions.directionToVector(direction)
                nextx, nexty = int(x + dx), int(y + dy)
                if not wallPosition[nextx][nexty]:
                    if (nextx, nexty) not in visited:
                        visited[(nextx, nexty)] = (node, direction)
                        queue.push((nextx, nexty))
    return len(solution)
コード例 #49
0
 def findpath(self, foodpos):
     initpos = foodpos
     nodes = Queue()
     nodes.push((initpos, []))
     closed = []
     while not nodes.isEmpty():
         curnode, acts = nodes.pop()
         if curnode in closed:
             continue
         closed.append(curnode)
         if self.isgoal(curnode):
             if len(acts) == 0:
                 return ['STOP']
             return acts
         succs = self.getsucc(curnode)
         for node in succs:
             newacts = acts.copy()
             newacts.append(node[1])
             nodes.push((node[0], newacts))
     return []
コード例 #50
0
def breadthFirstSearch(problem):
    # initialization part of the algorithm
    from util import Queue
    queue = Queue()
    queue.push(problem.getStartState())
    visited = {problem.getStartState(): (None, None)}
    solution = []
    while not queue.isEmpty() and not solution:
        # extract a node from the queue
        node = queue.pop()
        # if the node is a goal state, then compute solution
        if problem.isGoalState(node):
            solution = computeSolution(node, visited)
        if not solution:
            # take each successor of the current node and add it to the queue if not visited
            for successor in problem.getSuccessors(node):
                if successor[0] not in visited:
                    visited[successor[0]] = (node, successor[1])
                    queue.push(successor[0])
    return solution
コード例 #51
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    fringe = Queue()
    closed_set = set()
    action_list = list()
    current_state_list = [problem.getStartState(), []]
    while True:
        if problem.isGoalState(current_state_list[0]):
            action_list = current_state_list[1]
            break
        if current_state_list[0] not in closed_set:
            for i in problem.getSuccessors(current_state_list[0]):
                if i[0] not in closed_set:
                    fringe.push([i[0], current_state_list[1] + [i[1]]])
            closed_set.add(current_state_list[0])
        if fringe.isEmpty():
            break
        current_state_list = fringe.pop()
    return action_list
コード例 #52
0
def mazeDistance(start, end, walls):
    from util import Queue
    assert not walls[start[0]][start[1]], 'point1 is a wall: ' + str(start)
    assert not walls[end[0]][end[1]], 'point2 is a wall: ' + str(end)

    bfsQueue = Queue()
    statesExplored = set()
    bfsQueue.push((start, 0))

    while (not bfsQueue.isEmpty()):
        currentNode = bfsQueue.pop()
        if (currentNode[0] == end):
            return currentNode[1]
        successors = getSuccessorsForBFS(currentNode[0], walls)
        for successor in successors:
            if (successor not in statesExplored):
                bfsQueue.push((successor, currentNode[1] + 1))
                statesExplored.add(successor)

    return None
コード例 #53
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    open = Queue()
    cyclecheck = {}
    start = problem.getStartState()
    open.push((start, [], 0))
    cyclecheck[start] = []
    if problem.isGoalState(start):
        return []
    while not open.isEmpty():
        state, actions, cost = open.pop()
        cyclecheck[state] = actions
        if problem.isGoalState(state):
            return actions
        for suc in problem.getSuccessors(state):
            if suc[0] not in cyclecheck:
                cyclecheck[suc[0]] = suc[1]
                succ = (suc[0], actions + [suc[1]], suc[2] + cost)
                open.push(succ)
    return False
コード例 #54
0
ファイル: search.py プロジェクト: ychen0131/AI
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    [2nd Edition: p 73, 3rd Edition: p 82]
    """
    "*** YOUR CODE HERE ***"
    from game import Directions
    from util import Queue

    if (problem.isGoalState(problem.getStartState())):
        return []
    explored = []
    fringe = []
    leaves = Queue()
    leaves.push((problem.getStartState(), []))

    while (not leaves.isEmpty()):
        length = len(leaves.list)
        for i in range(length):
            node = leaves.pop()
            #print node
            explored.append(node[0])
            curState = node[0]
            actions = node[1]
            neighbors = problem.getSuccessors(curState)
            #           if problem.isGoalState(curState):
            #                 #actions.append(ele[])
            #                 #print len(actions)
            #                 return actions
            for ele in neighbors:
                if ele[0] not in explored and ele[0] not in fringe:
                    if problem.isGoalState(ele[0]):
                        actions.append(ele[1])
                        #print len(actions)
                        #print actions
                        return actions
                    fringe.append(ele[0])
                    leaves.push((ele[0], actions + [ele[1]]))

    print "Error: No Path Found!"
    return []
コード例 #55
0
ファイル: search.py プロジェクト: jd2695/Pacman
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    """
    "*** YOUR CODE HERE ***"
    from game import Directions
    s = Directions.SOUTH
    w = Directions.WEST
    n = Directions.NORTH
    e = Directions.EAST
    start = problem.getStartState()
    if problem.isGoalState(start):
        return []
    from util import Queue
    statesQueue = Queue()
    exploredSet = set([start])
    tup = (start,[])
    statesQueue.push(tup)
    while not statesQueue.isEmpty():
        tup1 = statesQueue.pop()
        state = tup1[0]
        path = tup1[1]
        if problem.isGoalState(state):
            return path
        successors = problem.getSuccessors(state)
        for succ in successors:
            coor = succ[0]
            move = succ[1]
            tempPath = list(path)
            if not coor in exploredSet:
                exploredSet.add(coor)
                if move == 'North':
                    tempPath.append(n)
                elif move == 'East':
                    tempPath.append(e)
                elif move == 'South':
                    tempPath.append(s)
                elif move == 'West':
                    tempPath.append(w)
                statesQueue.push((coor,tempPath))
    return []#nodes expanded, tiny=15, medium=269, big=620
コード例 #56
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""

    from util import Queue

    queue = Queue()  # queue data structure
    queue.push(problem.getStartState())
    visited_set = []  # for storing set of visited states
    path = []

    backTrackDict = {}  # dictionary for tracking path
    backTrackDict[problem.getStartState()] = [problem.getStartState(), '']
    visited_set.append(problem.getStartState())

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

        if (problem.isGoalState(node)):  # if it is a goal state, track path
            temp = node
            while (backTrackDict[temp][0] !=
                   temp):  # until it is a start state
                path.append(backTrackDict[temp][1])
                temp = backTrackDict[temp][0]

            path.reverse()
            return path

        else:
            children = problem.getSuccessors(node)
            for child in children:
                if (child[0] not in visited_set
                    ):  # push child to queue if not in visited set
                    queue.push(child[0])
                    visited_set.append(child[0])
                    if (child[0] not in backTrackDict):
                        backTrackDict[child[0]] = [
                            node, child[1]
                        ]  # add child as key to dictionary and (parent,action) as value

    "*** YOUR CODE HERE ***"
    util.raiseNotDefined()
コード例 #57
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"

    startState = problem.getStartState()
    bfsStack = Queue()
    bfsClosed = dict()
    # object the holds node properties
    activeNode = {
        'nodeAction': None,
        'nodeState': startState,
        'nodeParent': None
    }

    bfsStack.push(activeNode)
    while True:
        if bfsStack.isEmpty():
            break
        activeNode = bfsStack.pop()
        state = activeNode["nodeState"]
        if bfsClosed.has_key((state)):
            continue
        else:
            bfsClosed[state] = True
        if problem.isGoalState(state) == True:
            break
        for expandedNodes in problem.getSuccessors(state):
            if not bfsClosed.has_key((expandedNodes[0])):
                # push the child node with child node properties, important to save the parent path ("nodeParnt")
                bfsStack.push({
                    'nodeAction': expandedNodes[1],
                    'nodeState': expandedNodes[0],
                    'nodeParent': activeNode
                })
    actions = []
    while True:
        if activeNode["nodeAction"] == None:
            break
        actions.insert(0, activeNode["nodeAction"])
        activeNode = activeNode["nodeParent"]
    return actions
コード例 #58
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""

    from util import Queue

    visitedStates = []
    start_stateObj = problem.getStartState()
    fringe = Queue()
    fringe.push( (start_stateObj, [] ) )

    while not fringe.isEmpty():
        current_StateObj, curPath = fringe.pop()

        if problem.isGoalState(current_StateObj):
            return curPath

        if current_StateObj not in visitedStates:
            successorStates_tuple = problem.getSuccessors(current_StateObj)
            for stateTuple in successorStates_tuple:
                fringe.push( (stateTuple[0], curPath + [stateTuple[1]] ) )
            visitedStates.append(current_StateObj)
コード例 #59
0
def breadthFirstSearch(problem):
    """
  Search the shallowest nodes in the search tree first.
  """
    # define the node as (state, trajectory)

    from util import Queue
    queue, seen = Queue(), set()
    queue.push((problem.getStartState(), []))

    while not queue.isEmpty():
        state, trajectory = queue.pop()
        if state in seen:
            continue
        seen.add(state)
        if problem.isGoalState(state):
            return trajectory
        else:
            for successor, action, stepCost in problem.getSuccessors(state):
                if successor not in seen:
                    queue.push((successor, trajectory + [action]))
コード例 #60
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue

    queue = Queue()
    startState = problem.getStartState()
    visitedList = {}
    action = []
    cost = 0
    queue.push((startState, action, cost))
    while not queue.isEmpty():
        top = queue.pop()
        if problem.isGoalState(top[0]):
            return top[1]
        if top[0] not in visitedList:
            visitedList[top[0]] = True
            for successor_nodes, act, co in problem.getSuccessors(top[0]):
                if successor_nodes and successor_nodes not in visitedList:
                    queue.push((successor_nodes, top[1] + [act], top[2] + co))
    util.raiseNotDefined()