class QueueTheStack: "A container with a first-in-first-out (FIFO) queuing policy." def __init__(self): self.Stack1 = Stack() self.Stack2 = Stack() "add adequate number of stacks here" "*** WRITE CODE HERE ***" def push(self,item): self.Stack1.push(item); "Enqueue the 'item' into the queue" "*** WRITE CODE HERE ***" def pop(self): while (not self.Stack1.isEmpty()): self.Stack2.push(self.Stack1.pop()) toreturn = self.Stack2.pop() while (not self.Stack2.isEmpty()): self.Stack1.push(self.Stack2.pop()) return toreturn "dequeue the 'item' from the queue" "*** WRITE CODE HERE ***" def isEmpty(self): return self.Stack1.isEmpty() "returns true if the queue is empty" "***WRITE CODE HERE***"
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack frontier=Stack() 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): if not child.state in explored: frontier.push(child)
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [p 85]. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [Fig. 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ frontier = Stack() # A helper stack of (state,route_to_state) explored_set = set() # A set of state recording the explored nodes start = problem.getStartState() frontier.push((start,list())) while not frontier.isEmpty(): current_node = frontier.pop() if problem.isGoalState(current_node[0]): return current_node[1] successors = problem.getSuccessors(current_node[0]) explored_set.add(current_node[0]) for s in successors: if s[0] not in explored_set: current_route = list(current_node[1]) current_route.append(s[1]) frontier.push((s[0],current_route)) print "No route found!" return list()
def depthFirstSearch(problem): "Search the shallowest nodes in the search tree first. [p 81]" from util import Stack BFS1 = Stack() 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 depthFirstSearch(problem): """ Search the deepest nodes in the search tree first Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" '''util.raiseNotDefined()''' from util import Stack path=[] closedList=[] cost=0 fringe = Stack() node=[path, cost ,problem.getStartState()] fringe.push(node) while (1): if fringe.isEmpty(): raise Exception, 'no solutiion' newState=fringe.pop() if problem.isGoalState(newState[2]): return newState[0] if newState[2] not in closedList: closedList.append(newState[2]) for x in problem.getSuccessors(newState[2]): fringe.push([newState[0]+[str(x[1])],newState[1]+x[2],x[0]])
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ from util import Stack start = problem.getStartState() checkStack = Stack() checkStack.push((start,[])) visitedStates = [] while not checkStack.isEmpty(): popState, popDirection = checkStack.pop() for successors in problem.getSuccessors(popState): state, direction, cost = successors if not state in visitedStates: if problem.isGoalState(state): print state return popDirection + [direction] checkStack.push((state,popDirection+[direction])) visitedStates = visitedStates+[popState]
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ #Init variables currentCoordinate = problem.getStartState() #The current coordinate we are evaluating pathToCurrentCoordinate = [] #The current list we are using and updating fringeCoordinateList = Stack() #List of current edge coordinates, can have duplications fringeCoordinateList.push(currentCoordinate) previouslyVisitedCoordinatesList = [] #List of previously visited coordinates pathsToCoordinates = Stack() #List of lists of actions pathsToCoordinates.push(pathToCurrentCoordinate) #First run through 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
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack #: lista de nodos visitados closed = [] #: pila que hace la funcion de frontera frontier = Stack() # 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() # 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): frontier.push(Node( successor[0], node, successor[1], successor[2])) #: 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]
def hanoi (n, source, helper, target): if n==1: target.push(source.pop()) else: hanoi(n-1,source,target,helper) target.push(source.pop()) hanoi(n-1,helper,source,target) print "source " print temp = Stack() while not source.isEmpty(): t = source.pop() temp.push(t) print t while not temp.isEmpty(): t = temp.pop() source.push(t) print "helper " print temp = Stack() while not helper.isEmpty(): t = helper.pop() temp.push(t) print t while not temp.isEmpty(): t = temp.pop() helper.push(t) print "target" print temp = Stack() while not target.isEmpty(): t = target.pop() temp.push(t) print t while not temp.isEmpty(): t = temp.pop() target.push(t) print print
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [2nd Edition: p 75, 3rd Edition: p 87] Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" print "the problem is ", problem 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 Stack statesStack = Stack() exploredSet = set([start]) tup = (start,[]) statesStack.push(tup) while not statesStack.isEmpty(): tup1 = statesStack.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] #cost = succ[2] 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) statesStack.push((coor,tempPath)) return []
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in:""" loc_stack = Stack() visited_node = {} parent_child_map = {} direction_list = [] start_node = problem.getStartState() parent_child_map[start_node] = [] loc_stack.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_stack.isEmpty() == False): parent_node = loc_stack.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_stack.push(child_state) parent_child_map[child_state] = [parent_node,child_action] temp = temp + 1
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ from util import Stack from game import Directions s = Directions.SOUTH w = Directions.WEST n = Directions.NORTH e = Directions.EAST opened = Stack() #create an open stack start = problem.getStartState() closed = set([start]) #create a closed list with the root node 1st entry if problem.isGoalState(start): #failsafe in case root is goal return [] opened.push((start, [])) while not opened.isEmpty(): tup2 = opened.pop() #remove 1st item from open stack state = tup2[0] direction = tup2[1] if problem.isGoalState(state): return direction children = problem.getSuccessors(state) #generate children for child in children: #name both the coordinates and direction position = child[0] direct = child[1] list_of_paths = list(direction) if not position in closed: #add to closed list (if not already there) closed.add(position) #list_of_paths.append(direction) if direct == 'North': list_of_paths.append(n) elif direct == 'East': list_of_paths.append(e) elif direct == 'South': list_of_paths.append(s) elif direct == 'West': list_of_paths.append(w) #keeps track of all directions traveled in dfs opened.push((position,list_of_paths)) #add children to stack return []
def depthFirstSearch(problem): from game import Directions from util import Stack South = Directions.SOUTH West = Directions.WEST East = Directions.EAST North = Directions.NORTH stop = Directions.STOP """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ ans = [] ParentNode = {} direction = {} stack = Stack() startNode = problem.getStartState() visitedList = [] stack.push(startNode) if problem.isGoalState(startNode): return stop while stack.isEmpty() == False: currentNode = stack.pop() visitedList.append(currentNode) if problem.isGoalState(currentNode): goalPath = currentNode while goalPath != startNode: ans.append(direction[goalPath]) goalPath = ParentNode[goalPath] return ans[::-1] allCurrentSuccessor = problem.getSuccessors(currentNode) for Node in allCurrentSuccessor: if not Node[0] in visitedList: stack.push(Node[0]) ParentNode[Node[0]] = currentNode direction[Node[0]] = Node[1] return stop util.raiseNotDefined()
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack if problem.isGoalState(problem.getStartState()): return list() ##initialize the list of actions to return, frontier and explored set frontier = Stack() 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 = set() ##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.add(node[0]) ##looping through current state's successor states for state,action,stepCost in problem.getSuccessors(node[0]): ##add the action needed from current state to next state onto the action list oldActions = list(node[1]) oldActions.append(action) nextNode = [state, oldActions] ##push the node onto the frontier if it is unexplored if(state not in explored): frontier.push(nextNode) return None
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [p 85]. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [Fig. 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: """ from game import Directions s = Directions.SOUTH w = Directions.WEST n = Directions.NORTH e = Directions.EAST visitedlist = [] st = Stack() outputlist = [] st.push(problem.getStartState()) visitedlist.append(problem.getStartState()) recurseDFS(st,problem,visitedlist) if st.isEmpty(): print "No Path exist" else: while not st.isEmpty(): value = st.pop() if len(value) == 2: continue if value[1] == 'South': outputlist.append(s) elif value[1] == 'North': outputlist.append(n) elif value[1] == 'East': outputlist.append(e) elif value[1] == 'West': outputlist.append(w) return outputlist[::-1]
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [p 85]. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [Fig. 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ from game import Directions from util import Stack n=Directions.NORTH s=Directions.SOUTH e=Directions.EAST w=Directions.WEST explored=[] frontier=Stack() 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): return actions explored.extend(currentState) successors=problem.getSuccessors(currentState) for successor in successors: succState=successor[0] succAction=successor[1] if succState not in explored and succState not in frontierSet: frontierSet.append(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 []
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [2nd Edition: p 75, 3rd Edition: p 87] Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack Explored = {} Frontier = Stack() node = 0 current = problem.getStartState() Explored[current] = 1; succ = problem.getSuccessors(current) for k in succ: #print "initial push",k Frontier.push([k]); Explored[k[0]] = 1; 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 succ = problem.getSuccessors(node) for k in succ: if not (k[0] in Explored): Frontier.push(current + [k]); Explored[k[0]] = 1; sol = [] #print current for k in current: sol += [k[1]] # print sol return sol
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack nodes = Stack() closed = dict() moves = list() for var in problem.getSuccessors(problem.getStartState()): state = FringeState(var[0]) state.moves.append(Directions.convToDirection(var[1])) nodes.push(state) closed[problem.getStartState()] = True while(False == nodes.isEmpty()): current_node = nodes.pop() #print "Current node:", current_node if(closed.has_key(current_node.pos)): continue if(problem.isGoalState(current_node.pos)): print "Goal reached!" moves = current_node.moves break for var in problem.getSuccessors(current_node.pos): state = FringeState(var[0]) state.moves= copy.deepcopy(current_node.moves) state.moves.append(Directions.convToDirection(var[1])) nodes.push(state) closed[current_node.pos] = True return moves
def depthFirstSearch(problem): from util import Stack s = Stack() s.push((problem.getStartState(),[])) expanded = [] while not s.isEmpty(): top = s.pop() if problem.isGoalState(top[0]): return top[1] successors = problem.getSuccessors(top[0]) for successor in successors[::-1]: if not successor[0] in expanded: s.push((successor[0], top[1]+ [successor[1]])) expanded.append(top[0]) return []
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" path = Stack() explored = [] def depthSearch(state): explored.append(state)#record that this node is explored if problem.isGoalState(state): #check if goal return True #return to the higher level of the "depthSearch" suc = problem.getSuccessors(state) #get a list of triples(successor, action, stepCost) #the successor is the next state #e.g. [((5, 4), 'South', 1), ((4, 5), 'West', 1)] # suc = [triple for triple in suc if not triple[0] in explored] # for triple in suc: # explored.append(triple[0]) for triple in suc: # for every triple(successor, action, stepCost) if explored.__contains__(triple[0]):#check if the state is searched continue if depthSearch(triple[0]): #the recursive path.push(triple[1]) # if the lower level return true, record the action return True # which means this level also has found goal state return False depthSearch(problem.getStartState()) #The first call route = [] while (not path.isEmpty()): action = path.pop() #print action route.append(action) #return a list of action return route
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from game import Directions S = Directions.SOUTH W = Directions.WEST E = Directions.EAST N = Directions.NORTH 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 = Stack() frontier.push(problem.getStartState()) while (not frontier.isEmpty()): state = frontier.pop() #print "Current state: ", state explored.append(state) if (problem.isGoalState(state)): #print "Found..." path = backtracking(problem, state, parentChild) return path for successor in problem.getSuccessors(state): #print "Successor: ", successor if (not successor[0] in explored): parentChild.append((state, successor[1], successor[0])) frontier.push(successor[0]) return None
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [p 85]. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [Fig. 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack stack = Stack() 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 stack.push((successor, None)) while(not stack.isEmpty()): expansion = stack.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]): stack.push((successor, expansion[0]))
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [p 85]. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [Fig. 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack from game import Directions state = 0 action = 1 s = Stack() visited = [] cstate = problem.getStartState() s.push((cstate, [])) while(not s.isEmpty()): cstate, path = s.pop() if (problem.isGoalState(cstate)): return path visited.append(cstate) for x in problem.getSuccessors(cstate): if(visited.count(x[state]) != 0): continue nstate = x[state] npath = path + [x[action]] s.push((nstate, npath)) print("Path is not found")
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [p 74]. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [Fig. 3.18]. """ "*** YOUR CODE HERE ***" # import Stack and Directions from game import Directions from util import Stack from util import Queue # create closed set, fringe, and path closed = {} fringe = Stack() path = [] # get root node and add to fringe root = problem.getStartState() fringe.push((root, root, 'Stop')) # while nodes still exist on fringe while not fringe.isEmpty(): node = fringe.pop() if problem.isGoalState(node[0]): while node[2] != 'Stop': path.append(node[2]) node = closed[node[1]] path.reverse() return path closed[node[0]] = node children = problem.getSuccessors(node[0]) for child in children: if child[0] not in closed: fringe.push((child[0], node[0], child[1])) return None
def depthFirstSearch(problem): from util import Stack closedSet = set() # set of nodes already visited fringe = Stack() # stack 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 node = fringe.pop() state = node.state path = node.path # return the path if you reach the goal if problem.isGoalState(state): return path # if we have never visited this node before, expand it # and add it's succesors to the fringe elif state not in closedSet: closedSet.add(state) successors = problem.getSuccessors(state) # start at the first successor and if it can not be followed to the end # continue to the next successor of the level before retreating back a step for each in successors: # get information from the successor nextState, nextAction, cost = each # update the path to include the successor nextPath = list(path) 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 "Depth First Search was unable to find a solution." return None
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack # Get start state startState = problem.getStartState() # Visited position visted = [] # Stack contain on state of Pacman stackNode = Stack() stackNode.push((startState, [])) while(not stackNode.isEmpty()): # Get current node executing currentState, actions = stackNode.pop() if currentState not in visited: # Check current node is Goal? if problem.isGoalState(currentState): return actions #visted.append(currentState) seccessors = problem.getSuccessors(currentState) for state, action, cost in seccessors: if state not in visted: stackNode.push((state,actions + [action])) visited.append(state) return []
def depthAndBreadth(problem, doDepth): """ Helper function for depthFirstSearch and breadthFirstSearch """ # import Stack and Directions from game import Directions from util import Stack from util import Queue # create closed set, fringe, and path closed = {} if doDepth: fringe = Stack() else: fringe = Queue() path = [] # get root node and add to fringe root = problem.getStartState() fringe.push((root, root, 'Stop')) # while nodes still exist on fringe while not fringe.isEmpty(): node = fringe.pop() if problem.isGoalState(node[0]): while node[2] != 'Stop': path.append(node[2]) node = closed[node[1]] path.reverse() return path closed[node[0]] = node children = problem.getSuccessors(node[0]) for child in children: if child[0] not in closed: fringe.push((child[0], node[0], child[1])) return None
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: """ from util import Stack print("\n problem: ", problem, " ENd \n") DFS_stack = Stack() visited = [] path = [] if problem.isGoalState(problem.getStartState()): return [] DFS_stack.push((problem.getStartState(), [])) while (True): if DFS_stack.isEmpty(): return [] xy, path = DFS_stack.pop() visited.append(xy) if problem.isGoalState(xy): return path succ = problem.getSuccessors(xy) if succ: for child in succ: if child[0] not in visited: update_path = path + [child[1]] DFS_stack.push((child[0], update_path))
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ from util import Stack from game import Directions from sets import Set openList = Stack() firstNode = problem.getStartState() initialNodes = problem.getSuccessors(firstNode) closedList = Set([firstNode]) for stuff in initialNodes: openList.push([stuff[0], [stuff[1]]]) while not openList.isEmpty(): save = openList.pop() if not save[0] in closedList: if problem.isGoalState(save[0]): return save[1] else: closedList.add(save[0]) newNodes = problem.getSuccessors(save[0]) for stuff in newNodes: if not stuff[0] in closedList: openList.push([stuff[0], save[1] + [stuff[1]]]) print "Can't find a path" exit()
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print("Start:", problem.getStartState()) print("Is the start a goal?", problem.isGoalState(problem.getStartState())) print("Start's successors:", problem.getSuccessors(problem.getStartState())) """ "*** YOUR CODE HERE ***" from util import Stack path = [] visited = set() toVisit = Stack() #toVisit2 = [] start = problem.getStartState() pos_and_dir = [start, path] toVisit.push(pos_and_dir) current = pos_and_dir while (not toVisit.isEmpty()): current = toVisit.pop() visited.add(current[0]) if problem.isGoalState(current[0]): return current[1] successors = problem.getSuccessors(current[0]) for s in successors: pos, direct, _ = s new_dir = current[1] + [direct] if (pos not in visited): toVisit.push([pos, new_dir]) #toVisit2.append(pos) return current[1]
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print("Start:", problem.getStartState()) print("Is the start a goal?", problem.isGoalState(problem.getStartState())) print("Start's successors:", problem.getSuccessors(problem.getStartState())) """ "*** YOUR CODE HERE ***" startState = problem.getStartState() parent = startState from util import Stack children = problem.getSuccessors(startState) successors = Stack() visited = list() visited.append(startState) for child in children: holder = list() holder.append(child[1]) nextChild = Cell(child[0], holder, parent, child[2], child) successors.push(nextChild) while successors.isEmpty() == False: thisparent = successors.pop() visited.append(thisparent.getCell()) if problem.isGoalState(thisparent.getCell()): return thisparent.getPath() newchildren = problem.getSuccessors(thisparent.getCell()) for child in newchildren: if child[0] not in visited: updatePath = thisparent.getPath().copy() updatePath.append(child[1]) nextCell = Cell(child[0], updatePath, thisparent, child[2], child) successors.push(nextCell)
def DepthLimitedSearch(problem, current_max_depth): from util import Stack from util import Counter from game import Actions from game import GameStateData start_board_state=problem.getStartState() current_board_state=start_board_state list_of_actions=Stack() seen_game_states=Counter() seen_game_states.update({current_board_state: current_board_state}) while(True): current_possible_actions = problem.getActions(current_board_state) move_made=False if(problem.goalTest(current_board_state)): break if(current_max_depth <= len(list_of_actions.list)): most_recent_move=list_of_actions.pop() current_board_state= problem.getResult(current_board_state,Actions.reverseDirection(most_recent_move)) continue else: current_possible_actions = problem.getActions(current_board_state) possible_new_board_state = current_board_state if(current_possible_actions and not move_made): for i in range(len(current_possible_actions)): possible_new_board_state = problem.getResult(current_board_state,current_possible_actions[i]) print(current_possible_actions) if(possible_new_board_state not in seen_game_states.values()): #make the move and update the problem list_of_actions.push(current_possible_actions[i]) seen_game_states.update({possible_new_board_state: possible_new_board_state}) current_board_state=possible_new_board_state current_possible_actions = problem.getActions(current_board_state) #seen_game_states[seen_game_states.argMax()+1] = current_board_state continue if(not move_made): if(list_of_actions.isEmpty()): break most_recent_move=list_of_actions.pop() current_board_state= problem.getResult(current_board_state,Actions.reverseDirection(most_recent_move)) return list_of_actions.list
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from game import Directions from util import Stack 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) stack = Stack() # contains pairs. each pair's first elem is a list of actions. second elem is state stack.push([[], problem.getStartState()]) while (not stack.isEmpty()): top = stack.pop() # this is the top of the stack actions = top[0] state = top[1] if (state not in visited): if problem.isGoalState(state): return actions visited.append(state) for child in problem.getSuccessors(state): tempActions = actions[:] tempActions.append(child[1]) stack.push([tempActions, child[0]]) return None
def are_foods_in_same_cluster(food1, food2, game_state: GameState, agent: CaptureAgent, cluster_radius=0): """ :param food1: :param food2: :param game_state: :param agent: :param cluster_radius: inclusive :return: """ visited = set() stack = Stack() stack.push(food1) while not stack.isEmpty(): current_food = stack.pop() visited.add(current_food) if current_food == food2: return True for neighbor in get_neighbor(current_food): # although this food is connected with food1, this food is too far and not considered in the cluster if agent.getMazeDistance(current_food, food1) > cluster_radius: continue if neighbor in visited: continue x, y = neighbor if game_state.hasFood(x, y): stack.push(neighbor) return False
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack stack = Stack() actions=[] visited=[] start_pos=problem.getStartState() stack.push( [start_pos, actions] ) while not stack.isEmpty(): top_item = stack.pop() position_list = top_item[0] actions_list = top_item[1] if problem.isGoalState(position_list): return actions_list if position_list not in visited: visited.append(position_list) successor_nodes=problem.getSuccessors(position_list) for nodes in successor_nodes: succ_node=nodes[0] succ_action=nodes[1] if succ_node not in visited: nxt_action=actions_list+[succ_action] stack.push([succ_node,nxt_action]) '''startnode = problem.getStartState()
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ from game import Directions from util import Stack 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) stack = Stack() # contains pairs. each pair's first elem is a list of actions. second elem is state stack.push([[], problem.getStartState()]) while (not stack.isEmpty()): top = stack.pop() # this is the top of the stack actions = top[0] state = top[1] if (state not in visited): if problem.isGoalState(state): return actions visited.append(state) for child in problem.getSuccessors(state): tempActions = actions[:] tempActions.append(child[1]) stack.push([tempActions, child[0]]) return None
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print("Start:", problem.getStartState()) print("Is the start a goal?", problem.isGoalState(problem.getStartState())) print("Start's successors:", problem.getSuccessors(problem.getStartState())) """ "*** YOUR CODE HERE ***" # util.raiseNotDefined() # print("Start:", problem.getStartState()) # print("Is the start a goal?", problem.isGoalState(problem.getStartState())) # print("Start's successors:", problem.getSuccessors(problem.getStartState())) from util import Stack from game import Directions states = Stack() # 标记已经搜索过的状态集合 havesearched = [] states.push((problem.getStartState(), [])) # # 循环终止条件:遍历完毕/目标测试成功 while not states.isEmpty(): cur_node, actions = states.pop() if problem.isGoalState(cur_node): return actions if cur_node not in havesearched: expand = problem.getSuccessors(cur_node) havesearched.append(cur_node) for location, direction, cost in expand: # 判断状态是否重复 if (location not in havesearched): states.push((location, actions + [direction])) util.raiseNotDefined()
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack stack = Stack() stack.push((problem.getStartState(), [])) visited_state = [] while not stack.isEmpty(): state, actions_list = stack.pop() if state in visited_state: continue visited_state.append(state) if problem.isGoalState(state): return actions_list for next_state, next_direction, _ in reversed( problem.getSuccessors(state)): if next_state in visited_state: continue stack.push((next_state, actions_list + [next_direction])) util.raiseNotDefined()
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ from util import Stack from game import Directions actions = [] frontier = Stack() 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))) return actions util.raiseNotDefined()
def depthFirstSearch(problem): from util import Stack stk = Stack() obj = [problem.getStartState(),[],[problem.getStartState()]] # [ current location, [list of directions], [list of past locations] ] stk.push(obj) while not stk.isEmpty(): nowObj = stk.pop() nowLocation = nowObj[0] path = nowObj[1] pastLocations = nowObj[2] if problem.isGoalState(nowLocation): return path successorObjs = problem.getSuccessors(nowLocation) successorObjs.reverse() # Successors comes in North, South, East, West order but I want to visit South before North. hence, Reverse() for s in successorObjs: if s[0] not in pastLocations: # making temp lists to copy original ones because I only modify lists to put them on stack tmpPath = list(path) tmpPath.append(s[1]) tmpPastLocations = list(pastLocations) tmpPastLocations.append(s[0]) stk.push([s[0],tmpPath,tmpPastLocations])
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [2nd Edition: p 75, 3rd Edition: p 87] Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack pilha = Stack() explorados = [] acoes = [] inicial = (problem.getStartState(),None,None,0) "(Estado atual, Estado Pai, Aчуo, Custo)" pilha.push(inicial) while pilha.isEmpty() == False: noAtual = pilha.pop() explorados.append(noAtual[0]) 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 explorados: tupla = (est,noAtual,aco,cus) pilha.push(tupla)
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [2nd Edition: p 75, 3rd Edition: p 87] Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack initialState = problem.getStartState() actionList = [] closed = set() fringe = Stack() fringe.push((initialState, actionList)) while fringe.isEmpty() == False: node = fringe.pop() state = node[0] action = node[1] if problem.isGoalState(state) == True: return action if state not in closed: closed.add(state) children = problem.getSuccessors(state) for child in children: newActionList = action[:] newActionList.append(child[1]) fringe.push((child[0], newActionList)) return
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack from game import Directions # the component of tree is (state, the path to the state) start = problem.getStartState() tree = Stack() tree.push((start, [])) # store the visited state visited = [] while (not tree.isEmpty()): (state, path) = tree.pop() if (problem.isGoalState(state)): break visited.append(state) successors = problem.getSuccessors(state) for i in successors: if (i[0] not in visited): # visited.append(i[0]) tree.push((i[0], path + [i[1]])) return path util.raiseNotDefined()
def depthFirstSearch(problem): """ print("Start:", problem.getStartState()) print("Is the start a goal?", problem.isGoalState(problem.getStartState())) print("Start's successors:", problem.getSuccessors(problem.getStartState()))""" dfsStack = Stack() visitedStates = [] startState= problem.getStartState() dfsStack.push((startState, [])) while not dfsStack.isEmpty() and not problem.isGoalState(startState) : currNode, plan = dfsStack.pop() if currNode not in visitedStates: visitedStates.append(currNode) if problem.isGoalState(currNode): return plan child = problem.getSuccessors(currNode) for nextChild, action, cost in child: dfsStack.push((nextChild, plan + [action]))
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack from collections import defaultdict stack = Stack() visited = defaultdict() if problem.isGoalState(problem.getStartState()): return [] stack.push((problem.getStartState(), [])) visited[problem.getStartState()] = 1 while not stack.isEmpty(): coord, path = stack.pop() visited[coord] = 1 if problem.isGoalState(coord): return path successors = problem.getSuccessors(coord) for succ in successors: if succ[0] not in visited: stack.push((succ[0], path + [succ[1]])) return []
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [2nd Edition: p 75, 3rd Edition: p 87] Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack start = problem.getStartState() fringe = Stack() visited=[] path = [] if problem.isGoalState(start): return path fringe.push((start,path)) while not fringe.isEmpty(): state,path = fringe.pop(); if state not in visited: if problem.isGoalState(state): return path visited.append(state) for newstate,newpath,cost in problem.getSuccessors(state): if newstate not in visited: if problem.isGoalState(newstate): return path+[newpath] visited.append(newstate) fringe.push((newstate,path+[newpath]))
def depthFirstSearch(problem): from util import Stack from game import Directions visited = [] step = [] candidateState = Stack() candidateStep = Stack() entryState = problem.getStartState() candidateState.push(entryState) candidateStep.push('Stop') EdgeSet = {} while not candidateState.isEmpty(): currentState = candidateState.pop() currentStep = candidateStep.pop() visited.append(currentState) if problem.isGoalState(currentState): goalState = currentState finalStep = currentStep break else: tempCandidate = [] for candidate in problem.getSuccessors(currentState): if not visited.count(candidate[0]): tempCandidate.append(candidate) if len(tempCandidate) > 0: for candidate in tempCandidate: candidateState.push(candidate[0]) candidateStep.push(candidate[1]) EdgeSet[(candidate[0], candidate[1])] = (currentState, currentStep) currentState = goalState currentStep = finalStep while not currentState == entryState: pState = EdgeSet[(currentState, currentStep)] step.insert(0, currentStep) currentState = pState[0] currentStep = pState[1] return step
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [2nd Edition: p 75, 3rd Edition: p 87] Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" currentState = problem.getStartState() print(("Start: {}".format(currentState))) frontier = Stack() visitedNodes = set() frontier.push( (currentState, [])) # State and available actions (directions) # Continue as far as there are nodes to be explored while not frontier.isEmpty(): currentState, actions = frontier.pop() if currentState not in visitedNodes: visitedNodes.add(currentState) for successor, action, stepCost in problem.getSuccessors(currentState): if successor not in visitedNodes: if problem.isGoalState(successor): return actions + [action] frontier.push((successor, actions + [action])) return list()
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print("Start:", problem.getStartState()) print("Is the start a goal?", problem.isGoalState(problem.getStartState())) print("Start's successors:", problem.getSuccessors(problem.getStartState())) """ from util import Stack visited = [] path = [] stack = Stack() stack.push((problem.getStartState(), path)) while stack.isEmpty() is False: state, path = stack.pop() if state in visited: continue if problem.isGoalState(state): return path visited.append(state) successors = problem.getSuccessors(state) for node in successors: if node[0] not in visited: stack.push((node[0], path + [(node[1])])) return path
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from game import Directions from util import Stack # searched list of nodes closed = [] fringe = Stack() fringe.push([problem.getStartState(), ['start']]) while True: if fringe.isEmpty(): break currentNode = fringe.pop() if problem.isGoalState(currentNode[0]): currentNode[1].remove("start") print currentNode return currentNode[1] if currentNode[0] not in closed: closed.append(currentNode[0]) for childNode in problem.getSuccessors(currentNode[0]): newList = list(currentNode[1]) newList.append(childNode[1]) newNode = [childNode[0], newList] fringe.push(newNode)
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [2nd Edition: p 75, 3rd Edition: p 87] Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack from game import Directions states = Stack() states.push((problem.getStartState(), [])) used = set() used.add(problem.getStartState()) while not states.isEmpty(): state = states.pop() if problem.isGoalState(state[0]): return state[1] for successor in problem.getSuccessors(state[0]): if successor[0] in used: continue used.add(successor[0]) newpath = state[1][:] newpath.append(successor[1]) states.push((successor[0], newpath)) return [] util.raiseNotDefined()
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack startState = (problem.getStartState(), []) if problem.isGoalState(startState): return [] else: stackDFS = Stack() visited = [] path = [] stackDFS.push(startState) while not stackDFS.isEmpty(): pos, path = stackDFS.pop() visited.append(pos) if problem.isGoalState(pos): return path for p in problem.getSuccessors(pos): if p[0] not in visited: stackDFS.push((p[0], path + [p[1]])) return [] util.raiseNotDefined()
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print("Start:", problem.getStartState()) print("Is the start a goal?", problem.isGoalState(problem.getStartState())) print("Start's successors:", problem.getSuccessors(problem.getStartState())) """ "*** YOUR CODE HERE ***" from util import Stack dfs_stack = Stack() now_state = problem.getStartState() # 현재 상태 저장 dfs_stack.push((now_state, [])) # (현재 위치,현재 위치에 오기까지 경로) 튜플을 푸시 is_visited = [now_state] # 방문체크 list while not dfs_stack.isEmpty(): now_state = dfs_stack.pop() is_visited.append(now_state[0]) if problem.isGoalState(now_state[0]): return now_state[1] for (location, direction, cost) in problem.getSuccessors(now_state[0]): # 다음 노드 탐색 if location not in is_visited: dfs_stack.push( (location, now_state[1] + [direction])) # 방문한적이 없는 node 면 stack 에 푸시 return [] # 답안 존재 x
def depthFirstSearch(problem): # problem = (searchAgents.PositionSearchProblem) problem """ Search the deepest nodes in the search tree first Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack visitedNodes = [] stack = Stack() stack.push((problem.getStartState(), [])) while (not stack.isEmpty()): head = stack.pop() actions = head[1] state = head[0] if (state in visitedNodes): continue if (state not in visitedNodes): if problem.isGoalState(state): return actions visitedNodes.append(state) for child in problem.getSuccessors(state): tempActions = actions[:] tempActions.append(child[1]) stack.push((child[0], tempActions)) return None
def depthFirstSearch__ha(problem): from util import Stack stamp = [] #갔던 곳, list show_fringe = [] insertDirections = [] solD = Stack() fringe = Stack() # showfringe = [] child_fringe = Stack() fringe.push((problem.getStartState(), [], [])) stamp.append(problem.getStartState()) # 첫 위치 포함 while fringe.isEmpty() == False: node, d = fringe.pop() #LIFO print(node) stamp.append(node) #records Agent's step if problem.isGoalState(node) == True: return d #goal test for j in problem.getSuccessors(node): #child fringe print type(j) if j[0] not in stamp: # check rep # solD.push(insertDirections+[j[1]]) # insertDirections = insertDirections+[j[1]] act = [j[1]] n1 = list(node[1]) # print('-----------------------------') print type(act) print type(n1) # print act+n1 # print n1 fringe.push((j[0], act + n1, j[2])) print 'Fail......................................' return []
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: """ """ print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState())[1][2] """ a = set() from util import Stack vertexList = Stack() t = (problem.getStartState(), []) vertexList.push(t) "while (not bool(sum([problem.isGoalState(x[0]) for x in problem.getSuccessors(t[0])]))) and (not vertexList.isEmpty()):" while not vertexList.isEmpty(): t = vertexList.pop() if problem.isGoalState(t[0]): return t[1] if t[0] not in a: a.add(t[0]) for x in problem.getSuccessors(t[0]): vertexList.push((x[0], t[1] + [x[1]])) "[vertexList.push((x[0],t[1]+[x[1]])) for x in problem.getSuccessors(t[0]) if x[0] not in a]" "lastMove=[x[1] for x in problem.getSuccessors(t[0]) if problem.isGoalState(x[0])]" "return t[1]" "print t[1]+sum([x[1] for x in problem.getSuccessors(t[0])])" "*** YOUR CODE HERE ***" util.raiseNotDefined()
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ # set up to_visit = Stack() # stack or Queue of nodes to visit visited = set() # set of nodes visited paths = {} # dict from dot to paths # put first node start = problem.getStartState() to_visit.push(start) paths[start] = [] # process for each while not to_visit.isEmpty(): current = to_visit.pop() if problem.isGoalState(current): return paths[current] for (nextloc, dir, cost) in problem.getSuccessors(current): if not nextloc in visited: to_visit.push(nextloc) paths[nextloc] = paths[current] + [dir] visited.add(current) return None
def getAction(self, gameState): from util import Stack maxvalue = float("-inf") minvalue = float("inf") pFringe = Stack() value = [] countDepth = 0 for pa in gameState.getLegalActions(0): pFringe.push(pa) while pFringe.isEmpty() == False: pAction = pFringe.pop() gameState.generateSuccessor(0, pAction) while countDepth != self.depth: if countDepth != 0: for nextPA in gameState.getLegalActions(0): gameState.generateSuccessor(0, nextPA) agentIndex = 1 # minvalue = float("inf") while agentIndex != gameState.getNumAgents() - 1: for ga in gameState.getLegalActions(agentIndex): minvalue = min( minvalue, gameState.generateSuccessor(agentIndex, ga)) print 'Do ghost action?' agentIndex += 1 countDepth += 1 if countDepth == self.depth: # minscore = self.evaluationFunction(gameState) maxvalue = max(maxvalue, minvalue) scoremax = {maxvalue: pAction} # else: # for nextPA in gameState.getLegalActions(0): # gameState.generateSuccessor(0, nextPA) move = scoremax[max(scoremax.keys())] return move
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first [2nd Edition: p 75, 3rd Edition: p 87] Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm [2nd Edition: Fig. 3.18, 3rd Edition: Fig 3.7]. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" from util import Stack fringe = Stack() actions = [] closed = [] fringe.push((problem.getStartState(), actions, closed)) while not fringe.isEmpty(): curState, actions, closed = fringe.pop() closed.append(curState) for successor, action, stepCost in problem.getSuccessors(curState): if successor not in closed: if problem.isGoalState(successor): actions.append(action) return actions fringe.push((successor, actions + [action], closed)) return [] util.raiseNotDefined()
def depthFirstSearch(problem): """ Search the deepest nodes in the search tree first. Your search algorithm needs to return a list of actions that reaches the goal. Make sure to implement a graph search algorithm. To get started, you might want to try some of these simple commands to understand the search problem that is being passed in: print "Start:", problem.getStartState() print "Is the start a goal?", problem.isGoalState(problem.getStartState()) print "Start's successors:", problem.getSuccessors(problem.getStartState()) """ "*** YOUR CODE HERE ***" startState = problem.getStartState() visited = [] from util import Stack stack = Stack() stack.push((startState,[])) while (not stack.isEmpty()): topOfStack, action = stack.pop() visited.append(topOfStack) if (problem.isGoalState(topOfStack)): return action for succesor in problem.getSuccessors(topOfStack): if (succesor[0] not in visited): stack.push((succesor[0],action + [succesor[1]])) util.raiseNotDefined()