def myBreadthFirstSearch(problem): visited = {} frontier = util.Queue() frontier.push((problem.getStartState(), None)) while not frontier.isEmpty(): state, prev_state = frontier.pop() if problem.isGoalState(state): solution = [state] while prev_state != None: solution.append(prev_state) prev_state = visited[prev_state] return solution[::-1] if state not in visited: visited[state] = prev_state for next_state, step_cost in problem.getChildren(state): frontier.push((next_state, state)) return []
def iterativeDeepeningSearch(problem): """ Perform DFS with increasingly larger depth. Begin with a depth of 1 and increment depth by 1 at every step. """ resultado = 0 estado = problem.getStartState() caminho = util.Queue() limite = 1 # fronteira =[] # fronteira= set() visitados = util.Fronteira() visitados.add(estado,0) while True: resultado = busca_profundidade(problem,limite ,estado,caminho,visitados,1) if resultado == 1: break limite += 1 return caminho.list
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" queue = util.Queue() pushed = util.Counter() queue.push((problem.getStartState(), [])) pushed[problem.getStartState()] = 1 while not queue.isEmpty(): node, solution = queue.pop() if problem.isGoalState(node): return solution for neighbor in problem.getSuccessors(node): newSolution = solution + [neighbor[1]] if pushed[neighbor[0]] == 0: pushed[neighbor[0]] = 1 queue.push((neighbor[0], newSolution)) return []
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" queue = util.Queue() list_action = [] visited = [] start = (problem.getStartState() , list_action) queue.push(start) while not queue.isEmpty(): state , list_action = queue.pop() if problem.isGoalState(state): return list_action if state not in visited: visited.append(state) successors = problem.getSuccessors(state) for child_state, action, cost in successors: new_list_action = list_action[:] new_list_action.append(action) orther_queue = (child_state, new_list_action) queue.push(orther_queue)
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" queue = util.Queue() start = problem.getStartState() visited = [] visited.append(start) for sucessor in problem.getSuccessors(start): #print(sucessor) queue.push((sucessor[0], [sucessor[1]])) while queue is not None: (node, path) = queue.pop() if problem.isGoalState(node): #print(path) return path if node not in visited: visited.append(node) for sucessor in problem.getSuccessors(node): if sucessor not in visited: #print(sucessor) queue.push((sucessor[0], path + [sucessor[1]]))
def breadthFirstSearch(problem): """ Search the shallowest nodes in the search tree first. DICA: Utilizar util.PriorityQueue *** YOUR CODE HERE *** """ fringe = util.Queue() visitedList = [] fringe.push((problem.getStartState(), [], 0)) (state, toDirection, toCost) = fringe.pop() #add to visited points list visitedList.append(state) while not problem.isGoalState(state): #while n we search the path successors = problem.getSuccessors(state) #get next points for son in successors: if not son[0] in visitedList: fringe.push((son[0], toDirection + [son[1]], toCost + son[2])) visitedList.append(son[0]) # add to visited points (state, toDirection, toCost) = fringe.pop() return toDirection
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" # THINH CHANGED """ Ý tưởng là sử dụng queue, khởi tạo nó bằng hàm getStartedState() đã được cài đặt sản trong trong đó trả về node, actions và cost hiện tại. nếu mở rộng tìm kiếm cho đến khi isGoalState() == true """ bfsQueue = util.Queue() bfsQueue.push((problem.getStartState(), [], [])) # print("-------",bfsQueue) exploredNode = [] while not bfsQueue.isEmpty(): node, actions, curCost = bfsQueue.pop() if (not node in exploredNode): exploredNode.append(node) if problem.isGoalState(node): return actions for child, direction, cost in problem.getSuccessors(node): bfsQueue.push((child, actions + [direction], curCost + [cost])) return []
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" root = problem.getStartState( ) #Holds the root of the tree. The empty list is a spot holder to mimic the return value of the getSuccessors() method visited = [] #Holds all nodes that have been examined frontier = util.Queue() #Holds the nodes currently being examined frontier.push( (root, []) ) #Creates a priority queue to hold the states; empty list holds the actions used to get to the examined state while (not frontier.isEmpty()): v, actions = frontier.pop() #The state(node) being examined if (problem.isGoalState(v)): #End BFS if goal state is found return actions if (v not in visited): #Activate if state has not been examined yet visited.append(v) for coordinates, action, cost in problem.getSuccessors( v): #Examines each successor(child) of the examined state newActions = actions + [ action ] #Calculates the cost of moving to this state frontier.push((coordinates, newActions)) notFound() #Returns an 'error' if a goal state was not found
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" from game import Directions fringe = util.Queue() visitedList = [] fringe.push((problem.getStartState(), [], 0)) (state, toDirection, toCost) = fringe.pop() visitedList.append(state) while not problem.isGoalState(state): successors = problem.getSuccessors(state) for son in successors: if not son[0] in visitedList: fringe.push((son[0], toDirection + [son[1]], toCost + son[2])) visitedList.append(son[0]) (state, toDirection, toCost) = fringe.pop() return toDirection
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" open_data = util.Queue() startState = (problem.getStartState(), None, 0) open_data.push([startState]) visited_list = {startState[0]: 0} while not open_data.isEmpty(): node = open_data.pop() (end_state, _, _) = node[-1] actions = [action for (_, action, _) in node[1:]] if (problem.isGoalState(end_state)): return actions for succ in problem.getSuccessors(end_state): new_node = node + [succ] new_cost = sum([cost for (_, _, cost) in new_node]) state = succ[0] if (not state in visited_list): #or (new_cost < visited_list[state]): open_data.push(new_node) visited_list[state] = new_cost return []
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" # initialize the search tree using the initial state of problem queue = util.Queue() queue.push((problem.getStartState(), [])) visited = [] while not queue.isEmpty(): # choose a leaf node for expansion state, actions = queue.pop() # if the node contains a goal state then return the corresponding solution if problem.isGoalState(state): return actions # expand the node and add the resulting nodes to the search tree if state not in visited: visited.append(state) for successor, action, stepCost in problem.getSuccessors(state): if successor not in visited: queue.push((successor, actions + [action])) return False
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" fringe = util.Queue() discovered = set() fringe.push((problem.getStartState(), [])) while True: elem_pop = fringe.pop() curr_node, path_curr_node = elem_pop[0], elem_pop[1] if problem.isGoalState(curr_node): break else: if curr_node not in discovered: discovered.add(curr_node) successors = problem.getSuccessors(curr_node) for successor in successors: new_node, new_path = successor[0], successor[1] fin_path = path_curr_node + [new_path] fringe.push((new_node, fin_path)) final_path = path_curr_node return final_path
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" fringeCalculated = util.Queue() # Using Queue as we are implementing breadth first Search finalPath = [] # List of actions to be returned by this function visited = [] # List to keep track of the visited states fringeCalculated.push([(problem.getStartState() , None, 0)]) # Pushing the start state along with action and cost as a tuple into the Queue while not fringeCalculated.isEmpty(): # We will run the algorithm until the queue is empty or we will return the path we find Goal State consideredPath = fringeCalculated.pop() # Pop the list of states from the queue state = consideredPath[len(consideredPath)-1] # Get the last tuple in the state list if problem.isGoalState(state[0]): # Checking whether the state is a goal state and sending the final path if it is a goal state for path in consideredPath[1:]: finalPath.append(path[1]) # adding only directions return finalPath """Check whether the state is visited or not. Added in order to prevent infinite search. If not make we will now mark it as visited and we will get succeessors of the present node and we will append new paths upto these successors into the fringe.""" if state[0] not in visited: visited.append(state[0]) # If not make the state as visited for child in problem.getSuccessors(state[0]): # Get the successors of the current state path = consideredPath[:] path.append(child) # Append the child tuple into the state list popped fringeCalculated.push(path) # Appening the path list which we will check in next loops return finalPath
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" startState = problem.getStartState() visited = set() fringe = util.Queue() fringe.push((startState, ())) while not fringe.isEmpty(): currNode = fringe.pop() currState = currNode[0] currPlan = currNode[1] if problem.isGoalState(currState): return list(currPlan) if not currState in visited: visited.add(currState) paths = problem.getSuccessors(currState) for path in paths: newPlan = list(currPlan) newPlan.append(path[1]) nextNode = (path[0], tuple(newPlan)) if not path[0] in visited: fringe.push(nextNode)
def breadthFirstSearch(problem): """ Search the shallowest nodes in the search tree first. """ "*** YOUR CODE HERE ***" fringe = util.Queue() currentState = problem.getStartState() # push starting position to fringe. Fringe contains current node/directions fringe.push((currentState, [])) visited = [] # added starting node to visited nodes list since the code below does not append starting node to visited list visited.append(currentState) while not fringe.isEmpty(): (node, directions) = fringe.pop() if problem.isGoalState(node): return directions for successor, actions, cost in problem.getSuccessors(node): if not successor in visited: fringe.push((successor, directions + [actions])) visited.append(successor)
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" #same implementation as before, data structure = queue for bfs. frontier = util.Queue() explored_set = [] frontier.push((problem.getStartState(), [], 0)) while not frontier.isEmpty(): current = frontier.pop() if problem.isGoalState(current[0]): return current[1] if current[0] not in explored_set: explored_set.append(current[0]) for successor in problem.getSuccessors(current[0]): if successor[0] not in explored_set: new_path = current[1]+[successor[1]] #if problem.isGoalState(successor[0]): #return new_path frontier.push((successor[0], new_path, 0)) if frontier.isEmpty(): return []
def breadthFirstSearch(problem): """ Search the shallowest nodes in the search tree first. """ startNode = SearchNode(problem, problem.getStartState()) open = util.Queue() open.push(startNode) closed = [] while (not open.isEmpty()): current = open.pop() closed.append(current) if (problem.isGoalState(current.state)): break for successor in problem.getSuccessors(current.state): new = SearchNode(problem, successor[0], successor[1], current) if (new.state not in closed): closed.append(new) open.push(new) if (problem.isGoalState(current.state)): return current.path else: return []
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" fringe = util.Queue() node = {"state":problem.getStartState(), "path":[], "cost":0} fringe.push(node) explored = set() while (not fringe.isEmpty()): node = fringe.pop() if problem.isGoalState(node["state"]): return node["path"] else: if node["state"] not in explored: for nextnode in problem.getSuccessors(node["state"]): if nextnode[0] not in explored: nextnode = {"state":nextnode[0], "path":node["path"]+[nextnode[1]], "cost":node["cost"]+nextnode[2]} fringe.push(nextnode) explored.add(node["state"]) else: return []
def breadthFirstSearchPath(problem): """ Search the shallowest nodes in the search tree first. instead of giving the list of actions it returns the position of the closest one. """ frontier = util.Queue() visited = [] startNode = (problem.getStartState(), None, []) frontier.push(startNode) while not frontier.isEmpty(): curr = frontier.pop() currLoc = curr[0] currDir = curr[1] currPath = curr[2] if (currLoc not in visited): visited.append(currLoc) if (problem.isGoalState(currLoc)): return currLoc successors = problem.getSuccessors(currLoc) successorsList = list(successors) for i in successorsList: if i[0] not in visited: frontier.push((i[0], i[1], currPath + [i[1]]))
def generalSearch(problem, fn): dataStructure = {'bfs': util.Queue(), 'dfs': util.Stack()} root = problem.getStartState() try: visited = set() fringe = dataStructure[fn] fringe.push((root, [], 0)) while not fringe.isEmpty(): location, path, cost = fringe.pop() if problem.isGoalState(location): # print path return path if location not in visited: visited.add(location) for x, y, z in problem.getSuccessors(location): if x not in visited: fringe.push((x, path + [y], z)) return [] except Exception as e: print e return []
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" state_queue = util.Queue() set_states = set() state_queue.push((problem.getStartState(), [])) while not state_queue.isEmpty(): popped_state, popped_moves = state_queue.pop() if (popped_state in set_states): continue elif problem.isGoalState(popped_state): return popped_moves set_states.add(popped_state) for state, direction, cost in problem.getSuccessors(popped_state): if (state in set_states): continue state_queue.push((state, popped_moves + [direction])) return []
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" # "*** YOUR CODE HERE ***" startState = problem.getStartState() goalState = None # new stack Q = util.Queue() prevs = {} # initialize with startState Q.push(startState) prevs[str(startState)] = (None, 0) # breadth-first search rest of nodes while not Q.isEmpty(): state = Q.pop() # at goal? if problem.isGoalState(state): goalState = state break # check successors for (nextState, direction, cost) in problem.getSuccessors(state): if not str(nextState) in prevs: Q.push(nextState) prevs[str(nextState)] = (state, direction) # recover path from `prevs` record path = [] state = goalState while state != startState: prevState, direction = prevs[str(state)] path.insert(0, direction) state = prevState return path
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" # Return None if the start state is also the goal state # Don't need to move at all if problem.isGoalState(problem.getStartState()): return None explored = set() explored.add(problem.getStartState()) frontier = util.Queue() frontier_set = set() for action in problem.getSuccessors(problem.getStartState()): frontier.push([action]) frontier_set.add(action[0]) # while not frontier.isEmpty(): # print(frontier.pop()) # [((4, 5), 'West', 1)] # [((5, 4), 'South', 1)] while True: if frontier.isEmpty(): return False path = frontier.pop() state = path[-1][0] explored.add(state) if problem.isGoalState(state): actions = [x[1] for x in path] return actions for action in problem.getSuccessors(state): result_state = action[0] if result_state not in explored.union(frontier_set): new_path = list(path) new_path.append(action) frontier.push(new_path) frontier_set.add(result_state)
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" # currentPath stores the current Path taken to arrive at this node, visited checks if the node is already expanded before currentPath, visited = [], [] # Queue datastructure used to store all the successor nodes successorsQueue = util.Queue() # Direction taken to reach this node from the previous node direction = "None" successorsQueue.push((problem.getStartState(), direction, [])) # For each successor node, check if it is the goal, else find its successors while successorsQueue.isEmpty() == False: # getting node details from the queue node = successorsQueue.pop() currentState = node[0] direction = node[1] currentPath = node[2] # If node is already expanded, go to next node if currentState in visited: continue # Mark this current node as expanded as we will expand it now if it is not goal state visited.append(currentState) # If goal state, return back with the current Path if problem.isGoalState(currentState): print "Total Path cost", problem.getCostOfActions(currentPath) return currentPath # Get successors of current node and append it to the queue if it is not visited before successorsList = problem.getSuccessors(currentState) for x in successorsList: if x[0] not in visited: tempPath = list(currentPath) tempPath.append(x[1]) successorsQueue.push((x[0], x[1], tempPath))
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" queue = util.Queue() #Instantiate the queue path = [] #Collection of the path from start to finish visited = set() #Collection of the visited nodes startNode = [problem.getStartState(), []] #Starting node of the pacman util.Queue.push(queue, startNode) #Add starting node to queue to begin looping from is_goal = False #Set goal to false #Main loop, run while goal is not found while not is_goal: #Check if Queue is empty if not util.Queue.isEmpty(queue): (node, path) = util.Queue.pop(queue) #Extract node and path from the next node in queue #Check if the current node is the goal node, if it is, break out of the loop is_goal = problem.isGoalState(node) if is_goal: break #Check if the current node is already visited if node not in visited: visited.add(node) #Add the current node to visited nodes list successors = problem.getSuccessors(node) #Get successors of the current node #Iterate through the child nodes of the current node for successor in successors: #Ignore successors that are already visited if successor[0] not in visited: new_node_path = path + [successor[1]] #Create a new path and add the current successor's action to it new_node = (successor[0], new_node_path) #Create new node with the path information util.Queue.push(queue, new_node) #Add the new node with the path information to queue #Return the guide to the goal (e.g. ["West", "West", "South", ...]) return path
def breadthFirstSearch(problem): """ Search the shallowest nodes in the search tree first. [2nd Edition: p 73, 3rd Edition: p 82] """ def is_goal(x): """ Determine whether or not x is a goal state """ return problem.isGoalState(x) # Define the starting state start = problem.getStartState() # Setup the Queue data stack queue = util.Queue() queue.push((start, [])) # Initialise explored as an empty set explored = set() # Loop through while there's still more moves in the queue while not queue.isEmpty(): # Pop off the shallowest node in the frontier (node, path) = queue.pop() # If the node is a goal node, return the solution if is_goal(node): return path # Define successors for the leaf node successors = problem.getSuccessors(node) for state, action, cost in successors: # If state not already explored, add it to the list if state not in explored: # Add the tree node to the explored list explored.add(node) # Push the state, path and action onto the queue queue.push((state, path + [action])) """
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" #Set up of direction from game import Directions s = Directions.SOUTH w = Directions.WEST n = Directions.NORTH e = Directions.EAST #basic set up element for BFS #current state curr_state = problem.getStartState() #the next possible movement next_state_movement = util.Queue() #The dictionary for visited visited = {} #The list for visited in current state visited[curr_state] = [] #search goal state until hit the goal state while True: #look the every possible movement from getSuccessors for every_movement in problem.getSuccessors(curr_state): #only choose the un-visited state for next possible movement if every_movement[0] not in visited: #build up the stack tree for un-visited state information path = list(visited[curr_state]) path.append(every_movement[1]) next_state_movement.push((every_movement[0], path)) visited[every_movement[0]] = [] #after getting the next state movement then pop it out next_state = next_state_movement.pop() #update the new information to the information's record visited[next_state[0]] = next_state[1] curr_state = next_state[0] #if hit the goal state then return the result if problem.isGoalState(curr_state): return visited[curr_state]
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" "*** YOUR CODE HERE ***" visited = {} solution = [] queue = util.Queue() route = {} flag = False start = problem.getStartState() if problem.isGoalState(start): return solution queue.push((start, 'None', 0)) visited[start] = 'None' while not (queue.isEmpty() or flag): vertex = queue.pop() visited[vertex[0]] = vertex[1] if problem.isGoalState(vertex[0]): child = vertex[0] flag = True break for i in problem.getSuccessors(vertex[0]): if i[0] not in visited.keys() and i[0] not in route.keys(): route[i[0]] = vertex[0] queue.push(i) while (child in route.keys()): parent = route[child] solution.insert(0, visited[child]) child = parent return solution if problem.isGoalState(start): return solution util.raiseNotDefined()
def breadthFirstSearch(problem): """Search the shallowest nodes in the search tree first.""" possible_states = util.Queue() visited_states = [] possible_route = [] backtrace = [] current_state = problem.getStartState() possible_states.push( (current_state, backtrace) ) #Just because we need to start the loop with atleast one point so we can generalize. while problem.isGoalState(current_state) != True: info = possible_states.pop() #del backtrace[:] current_state = info[0] backtrace = info[1] #print backtrace #debug statement to see the form of our list # print(current_state) if current_state not in visited_states: #First step is to add the state to visiterd state visited_states.append(current_state) #backtrace.append(step) #Find its successors possible_successors = problem.getSuccessors(current_state) for i in range(0, len(possible_successors)): #path = backtrace + [possible_successors[i][1]] action = backtrace + [possible_successors[i][1]] possible_states.push((possible_successors[i][0], action)) #backtrace.pop() #print backtrace # print visited_states return backtrace util.raiseNotDefined()
def breadthFirstSearch(problem): """ Search the shallowest nodes in the search tree first The comments are mostly be the same with the DFS method; I will just mention the necessary parts of the code. Thanks. """ explored_set = {} #Using Queue instead of Stack in this uninformed search method. queue = util.Queue() successor = {} queue.push( (problem.getStartState(), []) ) while True: if queue.isEmpty(): break node = queue.pop() explored_set[node[0]] = node[1] if problem.isGoalState(node[0]): solution_item = node[0] break for succ in problem.getSuccessors(node[0]): #We are going to check the parents and the expanded nodes at the same time. #This is the difference of BFS comparing to DFS. if succ[0] not in explored_set.keys(): #Checking the explored set, otherwise that can continue forever. if succ[0] not in successor.keys(): successor[succ[0]] = node[0] queue.push(succ) solution = [] while(solution_item in successor.keys()): solution.insert(0, explored_set[solution_item]) solution_item = successor[solution_item] return solution