def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" # print ("Start's successors:", problem.getSuccessors(problem.getStartState())) fringe = util.PriorityQueue() fringe.push((problem.getStartState(), [], 0), 0) alreadyTraversed = [] while not fringe.isEmpty(): xy, direction, traveled = fringe.pop() if xy not in alreadyTraversed: alreadyTraversed.append(xy) if problem.isGoalState(xy): return direction for child, next, cost in problem.getSuccessors(xy): fringe.push((child, direction + [next], traveled + cost), traveled + cost) util.raiseNotDefined()
def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" #util.raiseNotDefined() visited = set() p_queue = util.PriorityQueue() p_queue.push((problem.getStartState(), []), 0) while not p_queue.isEmpty(): state, actions = p_queue.pop() if state in visited: continue visited.add(state) if problem.isGoalState(state): return actions for successor, action, stepCost in problem.getSuccessors(state): if successor not in visited: p_queue.push( (successor, actions + [action]), stepCost + problem.getCostOfActions(actions))
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE IF YOU WANT TO PRACTICE ***" fringe = util.PriorityQueue() explored = set() best_g = dict() initial_state = problem.getStartState() start_node = (initial_state, [], 0) priority = heuristic(initial_state, problem) fringe.push(start_node, priority) while not fringe.isEmpty(): curr_state, actions, acc_cost = fringe.pop() if curr_state not in explored or acc_cost < best_g[curr_state]: explored.add(curr_state) best_g[curr_state] = acc_cost if problem.isGoalState(curr_state): return actions for successor in problem.getSuccessors(curr_state): next_state, action, cost = successor new_cost = acc_cost + cost new_actions = actions + [action] new_priority = problem.getCostOfActions(new_actions) + heuristic(next_state, problem) fringe.update((next_state, new_actions, new_cost), new_priority) return None
def aStarSearch(problem, heuristic=nullHeuristic): "Search the node that has the lowest combined cost and heuristic first." "*** YOUR CODE HERE ***" frontier = util.PriorityQueue() currentCoordinate = problem.getStartState() currentMovesArray = [] currentHeuristic = heuristic(problem.getStartState(), problem) visited = [problem.getStartState()] while problem.isGoalState(currentCoordinate) != True: if frontier.length() % 1000 == 0: print frontier.length() for coordinate, direction, cost in problem.getSuccessors( currentCoordinate): if not coordinate in visited: frontier.push( (coordinate, currentMovesArray + [direction]), problem.getCostOfActions(currentMovesArray + [direction]) + heuristic(currentCoordinate, problem)) visited = visited + [coordinate] if frontier.isEmpty(): return [] currentCoordinate, currentMovesArray = frontier.pop() return currentMovesArray
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" # create a list called explored to store explored state # create a list called result to store the action # create a priority queue called priQueue to store the state and the result explored = [] result = [] priQueue = util.PriorityQueue() # find the start state from the problem start = problem.getStartState() # push the distance, start state and result with priority of 0 into the priority queue priQueue.push((0, start, result), 0) # store the start state into the explored explored.append(start) while(priQueue.isEmpty() == False): # pop the distance between start state and current state(called distance), current state, and result distance, start, result = priQueue.pop() # if the current state is the goal state then return the result if(problem.isGoalState(start) == True): return result # otherwise, find the successors of the current state successor = problem.getSuccessors(start) for success in successor: # if the successor of the current state does not find in the explored, then add the successor of the current state into the explored # add the action cost of the successor in the distance and add the action of the successor in the result # set the priority as the sum of new distance and the result of heuristic(successor state, problem) # update the new distance, successor state and new result with the new priority in the priority queue if(explored.count(success[0]) == 0): explored.append(success[0]) priQueue.update((distance + success[2], success[0], result + [success[1]]), distance + success[2] + heuristic(success[0],problem)) # if the successor state is the goal state, then add the action cost of the successor in the distance and add the action of the successor in the result # se the priority as the sum of new distance and the result of heuristic(successor state, problem) # update the new distance, successor state and new result with the new priority in the priority queue if(problem.isGoalState(success[0]) == True): priQueue.update((distance + success[2], success[0], result + [success[1]]), distance + success[2] + heuristic(success[0],problem)) util.raiseNotDefined()
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" heap = util.PriorityQueue() cur_cost, actions = {}, {} rootNode = problem.getStartState() cur_cost[rootNode] = 0 actions[rootNode] = () heap.push(rootNode, 0) while not heap.isEmpty(): node = heap.pop() if problem.isGoalState(node): return list(actions[node]) successors = problem.getSuccessors(node) for i in successors: if not (i[0] in cur_cost and i[2] + cur_cost[node] > cur_cost[i[0]]): cur_cost[i[0]] = i[2] + cur_cost[node] heap.update(i[0], cur_cost[i[0]] + heuristic(i[0], problem)) actions[i[0]] = actions[node] + ( i[1], ) #storing in tuple saves memory
def a_star_search(problem, heuristic=null_heuristic): """Search the node that has the lowest combined cost and heuristic first.""" """ start is the start state from problem, exploredState is an array of the state being explored fringe is priority queue in uniform cost search, fringe adds the tuple of the start state and an array, and the heuristic from null_heuristic """ start = problem.get_start_state() exploredState = [] fringe = util.PriorityQueue() fringeTuple = (start, []) fringe.push(fringeTuple, null_heuristic(start, problem)) astarCost = 0 """ Main Loop checks if fringe is not empty then checks if goal state, if goal state then actions are returned otherwise get the successors of the current state then check if the coordinates are within the exploredState and then add the coordinates to the exploredState array and add the actions to get to that coordinate state, also adds the heuristic but it is using null heuristic """ while not fringe.is_empty(): state, actions = fringe.pop() if problem.is_goal_state(state): return actions if state not in exploredState: successors = problem.get_successors(state) for successor in successors: coordinates = successor[0] if coordinates not in exploredState: directions = successor[1] astarActions = actions + [directions] astarCost = problem.get_cost_of_actions( astarActions) + heuristic(coordinates, problem) fringe.push((coordinates, actions + [directions]), astarCost) exploredState.append(state) return actions
def aStarSearch(self, goals): init_state = self.getCurrentObservation().getAgentState( self.index).getPosition() for goal in goals: init_node = model.make_root_node(init_state) frontier = util.PriorityQueue() frontier.push(init_node, 0) explored_set = [] while not frontier.isEmpty(): node = frontier.pop() if node["position"] not in explored_set: explored_set.append(node["position"]) if goal == node["position"]: if node["action"] == None: continue return model.make_actions(node)[0] for successor in self.getSuccessor(node["position"]): #succ_actions = StateModel.make_actions() succ_node = model.make_succ_node( node, successor[0], successor[1]) actions = model.make_actions(succ_node) g = len(actions) h = manhattanHeuristic(succ_node["position"], goal) f = g + h frontier.update(succ_node, f) #if no action has returned(dead end) if len(goals) != 0: succ = [] act = [] succ = self.getSuccessor(init_state) print "position", init_state act = [a[1] for a in succ] print "act", act if len(act) > 0: return random.choice(act) return 'Stop'
def minimax(self, gameState, maxi, depth): if self.isTerminal(gameState) or depth == 0: return (self.evaluationFunctionMinimax(gameState), Directions.STOP) childeren = util.PriorityQueue() if maxi: actions = gameState.getLegalActions(0) for a in actions: succsorGamestate = gameState.generateSuccessor(0, a) child = self.minimax(succsorGamestate, not maxi, depth - 1) childeren.push((child[0], a), -child[0]) if not maxi: actionslists = [] for i in range(gameState.getNumAgents() - 1): actionsghost = [] for a in gameState.getLegalActions(i + 1): actionsghost.append((a, i + 1)) actionslists.append(actionsghost) actions = self.getSenarios(actionslists) for a in actions: succsorGamestate = self.getSuccessor(gameState, a) child = self.minimax(succsorGamestate, not maxi, depth) childeren.push((child[0], a), child[0]) return childeren.pop()
def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" openList = util.PriorityQueue() closedList = [] currentState = problem.getStartState() pathUntilNow = [] currentNode = (currentState, pathUntilNow, 0) openList.push(currentNode, 0) while not openList.isEmpty(): currentNode = openList.pop() currentState = currentNode[0] pathUntilNow = currentNode[1] pathCost = currentNode[2] if currentState in closedList: continue if problem.isGoalState(currentState): return pathUntilNow closedList.append(currentState) successors = problem.getSuccessors(currentState) for nextState, nextAction, nextActionCost in successors: nextNode = (nextState, pathUntilNow + [nextAction], pathCost + nextActionCost) openList.update(nextNode, pathCost + nextActionCost) return [] util.raiseNotDefined()
def uniformCostSearch(problem): """Search the node of least total cost first.""" start_state = problem.getStartState() visited_node = {start_state: []} UCS_pq = util.PriorityQueue() UCS_pq.push(start_state, 0) while not UCS_pq.isEmpty(): expand_node = UCS_pq.pop( ) #pop and get item (not a tuple with priority) if (problem.isGoalState(expand_node)): return visited_node[expand_node] pre_path = visited_node[expand_node] successor = problem.getSuccessors(expand_node) for next in successor: if next[0] not in visited_node or problem.getCostOfActions( visited_node[next[0]]) > problem.getCostOfActions( pre_path + [next[1]]): visited_node[next[0]] = pre_path + [next[1]] UCS_pq.update(next[0], problem.getCostOfActions(visited_node[next[0]])) return visited_node[expand_node]
def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" # use PriorityQueue to implement UCS, PriorityQueue pop out item with lowest priority open = util.PriorityQueue() # implement node as a tuple of succ tuples start_state = problem.getStartState() node = ((start_state, None, 0), ) open.push(node, 0) # seen is implemented for cycle checking seen = {start_state: 0} while not open.isEmpty(): current_node = open.pop() current_state = current_node[-1][0] actions = [] #get list of actions for state, action, cost in current_node: if action is not None: actions.append(action) current_cost = problem.getCostOfActions(actions) # cost checking for cycle checking if current_cost <= seen[current_state]: if problem.isGoalState(current_state): return actions sucessors = problem.getSuccessors(current_state) for succ in sucessors: #cycle checking next_cost = current_cost + succ[2] if (not succ[0] in seen) or (next_cost < seen[succ[0]]): open.push(current_node + (succ, ), next_cost) seen[succ[0]] = next_cost return False
def aStarSearch(problem, heuristic=nullHeuristic): # the nodes we've expanded visited = [] # all nodes we could possibly expand frontier = util.PriorityQueue() # every node is added here as soon as it is created so we know when we don't need to expand it seenNodes = [] # creating the starting node curr = Node(problem.getStartState(), None, None, 0) visited.append(curr) while problem.goalTest(curr.state) == False: # create a node for each possible action we could expand from our current position actions = problem.getActions(curr.state) for action in actions: n = Node(problem.getResult(curr.state, action), curr, action, problem.getCost(curr.state, action)) # if we haven't seen this node, calculate its f value and add/update it in the priority queue if n not in seenNodes: f = n.path_cost + heuristic(n.state, problem) frontier.update(n, f) seenNodes.append(n) # pop the val with the lowest f from the frontier set curr = frontier.pop() visited.append(curr) # trace our path back from the end using the final current node path = [] while curr.parent: path.insert(0, curr.action) curr = curr.parent return path
def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" # Strictly follow the sudocode in the textbook for BFS, change the data structure to priority Q node = problem.getStartState() fringe = util.PriorityQueue() explored = set() solution = [] fringe.push((node, solution), 0) while not fringe.isEmpty(): # Run out of nodes, failed to find a solution node, curPath = fringe.pop() if problem.isGoalState(node): return curPath if not node in explored: explored.add(node) nextmove = problem.getSuccessors(node) for onemove in nextmove: child, nextDir = onemove[0], onemove[1] if (child not in explored) or (problem.isGoalState(child)): fringe.update( (child, curPath + [nextDir]), problem.getCostOfActions(curPath + [nextDir])) util.raiseNotDefined()
def uniformCostSearch(problem): visited = [] pq = util.PriorityQueue( ) # Create a priority queue data structure called pq elem1 = problem.getStartState() # Get the starting position of Pacman og = 0 visited.append( elem1) # Append the starting position on already traversed list path = [] tpath = [] while (problem.isGoalState(elem1) == False ): # Expand all the neighbours till goal is reached sitr = iter(problem.getSuccessors(elem1)) for elem in sitr: if (elem[0] not in visited): path = tpath[:] path.append(elem[1]) g = elem[2] + og path.append(g) path.append(elem[0]) pq.push(path, g) visited.append(elem1) while ( pq.isEmpty() == False ): # Extract elements from priority queue till we find unvisited node tpath = pq.pop() elem1 = tpath.pop() og = tpath.pop() if (elem1 not in visited): break return tpath
def aStarSearch(problem, heuristic=nullHeuristic): "Search the node that has the lowest combined cost and heuristic first." "*** YOUR CODE HERE ***" # exploracao: uma filha de prioridades de tuplas contendo estados e listas # de acoes necessarias para se alcancar um estado. # problem.getStartState () e o estado inicial e a lista de acoes inicial # e vazia (como esperado) exploracao = util.PriorityQueue() # estadosVisitados - uma lista contendo os estados visitados estadosVisitados = [] # segundo cormen - enqueue s (Start State) in Q # a lista vazia representa as acoes necessarias para # se alcancar o estado inicial exploracao.push((problem.getStartState(), []), 0) while not exploracao.isEmpty(): estadoCorrente, acoes = exploracao.pop() for e, a, c in problem.getSuccessors(estadoCorrente): if e not in estadosVisitados: # Quando o estado objetivo e alcancado, retorna-se as # acoes que o levaram a chegar ali if problem.isGoalState(e): return acoes + [a] # adiciona-se o ultimo estado explorado e as acoes # necessarias para chegar ate ele na fila de exploracao # o custo no a* e dado pelo custo para se executar as acoes mais o custo # oriundo da heuristica exploracao.push((e, acoes + [a]), problem.getCostOfActions(acoes + [a]) + heuristic(e, problem)) estadosVisitados.append(e) estadosVisitados.append(estadoCorrente) return []
def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" heap = util.PriorityQueue() cur_cost, actions = {}, {} rootNode = problem.getStartState() cur_cost[rootNode] = 0 actions[rootNode] = () heap.push(rootNode, 0) while not heap.isEmpty(): node = heap.pop() if problem.isGoalState(node): return list(actions[node]) successors = problem.getSuccessors(node) for i in successors: if not (i[0] in cur_cost and i[2] + cur_cost[node] > cur_cost[i[0]]): cur_cost[i[0]] = i[2] + cur_cost[node] heap.update(i[0], cur_cost[i[0]]) actions[i[0]] = actions[node] + ( i[1], ) #storing in tuple saves memory
def aStarSearch(problem, heuristic=nullHeuristic): "Search the node that has the lowest combined cost and heuristic first." "*** YOUR CODE HERE ***" # Queue -> PriorityQueue will result in UCS fringe, visited = util.PriorityQueue(), [] # push the root with an empty list which will track the path of nodes from the root # cost is 0 since it is the root node fringe.push((problem.getStartState(), []), 0) while fringe: current_node = fringe.pop() current_path = current_node[1] # if goal is found, return its path from root if problem.isGoalState(current_node[0]): return current_path else: if current_node[0] not in visited: visited.append(current_node[0]) for successor in problem.getSuccessors(current_node[0]): # add a path to successors and stack them up in the fringe successor_path = current_path + [successor[1]] # calculates the total path cost of root node to successor node before pushing to the queue # add heuristics to do aStar fringe.push((successor[0], successor_path), problem.getCostOfActions(successor_path) + heuristic(successor[0], problem))
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" trace = util.PriorityQueue() starting_state = problem.getStartState() cost = 0 trace.push((starting_state, list(), cost), cost) # empty list will eventually hold the actions taken to reach current element # placeholder will carry on the costs visited_states = set() while not trace.isEmpty(): curr_state, actions, cost = trace.pop() if curr_state not in visited_states: if problem.isGoalState(curr_state): # print "Path:: {}".format(actions) return actions successors = problem.getSuccessors(curr_state) for successor in successors: trace.push( (successor[0], actions[:] + [successor[1]], cost + successor[2]), heuristic(successor[0], problem) + cost + successor[2]) visited_states.add(curr_state)
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" priorityQueue = util.PriorityQueue() visited = set() distance = {} startState = problem.getStartState() priorityQueue.push((startState, []), 0 + heuristic(startState, problem)) distance[startState] = 0 while not priorityQueue.isEmpty(): currState, directions = priorityQueue.pop() if currState in visited: continue visited.add(currState) dirCost = distance[currState] if problem.isGoalState(currState): return directions successors = problem.getSuccessors(currState) for succ in successors: succState = succ[0] succDirection = succ[1] succCost = succ[2] if succState in distance and (distance[succState] <= dirCost + succCost): ''' the distance for the successor state is already accounted for and <= total cost) ''' continue elif succState in distance: ''' update the successor direction and cost in PQ ''' priorityQueue.update((succState, directions + [succDirection]), dirCost + succCost + heuristic(succState, problem)) else: ''' add in new node into PQ ''' priorityQueue.push((succState, directions + [succDirection]), dirCost + succCost + heuristic(succState, problem)) distance[succState] = dirCost + succCost util.raiseNotDefined()
def uniformCostSearch(problem): "Search the node of least total cost first. " "*** YOUR CODE HERE ***" start = problem.getStartState() fringe = util.PriorityQueue() history = [start] fringe.push(((start, []), []), 0) while not fringe.isEmpty(): parent, path = fringe.pop() if problem.isGoalState(parent[0]): return path + [parent[1]] for n in problem.getSuccessors(parent[0]): if n[0] not in history: if problem.isGoalState(n[0]): return path + [n[1]] history.append(n[0]) fringe.push((n, path + [n[1]]), problem.getCostOfActions(path + [n[1]])) return path
def aStarSearch(problem, heuristic=nullHeuristic): "Search the node that has the lowest combined cost and heuristic first." visited = [] fringe = util.PriorityQueue() start = problem.getStartState() fringe.push((start, list()), heuristic(start, problem)) while not fringe.isEmpty(): state, actions = fringe.pop() if problem.isGoalState(state): return actions visited.append(state) for state, dir, cost in problem.getSuccessors(state): if state not in visited: newactions = actions + [dir] score = problem.getCostOfActions(newactions) + heuristic(state, problem) fringe.push( (state, newactions), score) return [] util.raiseNotDefined()
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" fringe=util.PriorityQueue() explored=set() startStateBlock=problem.getStartState() gcost=0 hcost=manhattanHeuristic(startStateBlock,problem) #hcost=euclindean_distance(startStateBlock,problem) fcost=gcost+hcost fringe.push((startStateBlock,[]),fcost) while(not fringe.isEmpty()): state=fringe.pop() stateBlock=state[0] statePath=state[1].copy() explored.add(stateBlock) if (problem.isGoalState(stateBlock)): return statePath children=problem.getSuccessors(stateBlock) for child in children: actionToReachChild=child[1] gcost=child[2] hcost=manhattanHeuristic(child[0],problem) # hcost=euclindean_distance(child[0],problem) fcost=gcost+hcost childPath=statePath.copy() childPath.append(actionToReachChild) openList=[x[0] for x in fringe.heap if x[0]==child[0]] inProcess=child[0] in explored or child[0] in openList if (not inProcess): fringe.push((child[0],childPath),fcost) elif (child[0] in openList): fringe.update((child[0],childPath),fcost) return []
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" # Use a priority queue, so the cost of actions is calculated with a provided heuristic fringe = util.PriorityQueue() # Make an empty list of explored nodes visited = [] # Make an empty list of actions actionList = [] # Place the starting point in the priority queue fringe.push((problem.getStartState(), actionList), heuristic(problem.getStartState(), problem)) while fringe: node, actions = fringe.pop() if not node in visited: visited.append(node) if problem.isGoalState(node): return actions for successor in problem.getSuccessors(node): coordinate, direction, cost = successor nextActions = actions + [direction] nextCost = problem.getCostOfActions(nextActions) + \ heuristic(coordinate, problem) fringe.push((coordinate, nextActions), nextCost) return []
def aStarSearch(problem, heuristic=nullHeuristic): """Search the node that has the lowest combined cost and heuristic first.""" "*** YOUR CODE HERE ***" # Queue border = util.PriorityQueue() # Visited nodes visitedNode = [] # Actions actionsX = [] # Starting point border.push((problem.getStartState(), actionsX), heuristic(problem.getStartState(), problem)) while border: node, actions = border.pop() if not node in visitedNode: visitedNode.append(node) if problem.isGoalState(node): return actions for successor in problem.getSuccessors(node): coordinate, direction, cost = successor nextActions = actions + [direction] nextCost = problem.getCostOfActions(nextActions) + \ heuristic(coordinate, problem) border.push((coordinate, nextActions), nextCost) return []
def uniformCostSearch(problem): """Search the node of least total cost first.""" frontier = util.PriorityQueue() frontier.push(makeNode(problem.getStartState()), 0) closed = [] while not frontier.isEmpty(): node = frontier.pop() if problem.isGoalState(node.getState()): return node.getPath() closed.append(node.getState()) for successor in problem.getSuccessors(node.getState()): newnode = makeNode(successor[0], node, successor) if newnode.getState() not in closed and not heapContains(frontier.heap, newnode): frontier.push(newnode, newnode.getCost()) else: if heapContainsHigherCost(frontier.heap, newnode): frontier.update(newnode, newnode.getCost()) print "Deu ruim no uniform cost search" return []
def uniformCostSearch(problem): """Search the node of least total cost first.""" "*** YOUR CODE HERE ***" # the code will be the same as the above searches, with the addition of using a # priority queue and adding a cost to each state fringe = util.PriorityQueue() fringe.push([problem.getStartState(), 0, []], 0) explored = [] while not (fringe.isEmpty()): [state, cost, path] = fringe.pop() if (problem.isGoalState(state)): return path if not state in explored: explored.append(state) for child_state, child_action, child_cost in problem.getSuccessors(state): new_cost = cost + child_cost new_path = path + [child_action] fringe.push([child_state, new_cost, new_path], new_cost)
def uniformCostSearch(problem): """Search the node of least total cost first.""" state = problem.getStartState() frontier = util.PriorityQueue() start_node = Node(state, None, None) frontier.push(start_node, 0) visited = [] #log state while not frontier.isEmpty(): node = frontier.pop() if node.getNState() in visited: continue visited.append(node.getNState()) if problem.isGoalState(node.getNState()): actions = [] while node.getNAction() is not None: actions.append(node.getNAction()) node = node.getPreNode() actions.reverse() return actions successorList = problem.getSuccessors(node.getNState()) for successor in successorList: n = Node(successor[0], successor[1], node, node.getCost() + successor[2]) frontier.push(n, n.getCost())
def aStarSearch(problem, heuristic=nullHeuristic): ''' Pay clos attention to util.py- specifically, args you pass to member functions. Key Point: If a node is already present in the queue with higher path cost, you'll update its cost (Similar to pseudocode in figure 3.14 of your textbook.). Be careful, autograder cannot catch this bug. ''' startnode = problem.getStartState() #print(startnode) if problem.isGoalState(startnode): return [] myqueue = util.PriorityQueue() visited = [] myqueue.push((startnode, [], 0), heuristic(startnode, problem)) while not myqueue.isEmpty(): # (currentnode, actions, pcost) item = myqueue.pop() #print(item[0][0]) if item[0][0] not in visited: visited.append(item[0][0]) if problem.isGoalState(item[0][0]): return item[0][1] #print("here") for data in problem.getSuccessors(item[0][0]): new = item[0][1] + [data[1]] priority = item[1] + data[2] myqueue.push((data[0], new, priority), priority + heuristic(data[0], problem))
def uniformCostSearch(problem): """Search the node of least total cost first.""" discovered = set() root = ((problem.getStartState(), [])) pQueue = util.PriorityQueue() pQueue.push(root, 0) while not pQueue.isEmpty(): state, directions = pQueue.pop() if state not in discovered: discovered.add(state) if problem.isGoalState(state): return directions for successor, action, stepCost in problem.getSuccessors(state): if successor not in discovered: #print(successor) #print(actions) getCost = stepCost + problem.getCostOfActions(directions) pQueue.push((successor, directions + [action]), (getCost))