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): stack = Stack(); parentNode = []; successors = []; visitedNodes = [] parentChildMapList = {} stack.push(problem.getStartState()) currentState = problem.getStartState() #need to remove while problem.isGoalState(currentState) is False and problem.isGoalState(currentState[0]) is False: if(currentState == problem.getStartState()): successors = problem.getSuccessors(currentState) visitedNodes.append(currentState) else: successors = problem.getSuccessors(currentState[0]) visitedNodes.append(currentState[0]) if successors != None and len(successors) > 0 : parentNode.append(currentState) for node in successors: if(visitedNodes.__contains__(node) == False and visitedNodes.__contains__(node[0]) == False): stack.push(node) parentChildMapList[node] = currentState tempCurrentNode = stack.pop() if(visitedNodes.__contains__(tempCurrentNode) == False and visitedNodes.__contains__(tempCurrentNode[0]) == False): currentState = tempCurrentNode else: currentState = stack.pop() validDirections = [] firstState = currentState while firstState != problem.getStartState(): validDirections.append(firstState[1]) firstState = parentChildMapList[firstState] validDirections.reverse() return validDirections util.raiseNotDefined()
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()) """ "*** YOUR CODE HERE ***" stateStack = Stack() state = problem.getStartState() state = [(state, "Stop", 0)] stateStack.push(state) while not problem.isGoalState(state[len(state) - 1][0]): state = stateStack.pop() successors = problem.getSuccessors(state[len(state) - 1][0]) for successor in successors: if successor[0] not in [position[0] for position in state]: stateStack.push(state + [successor]) return [direction[1] for direction in state]
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): successor_idx = {'dir': 1, 'state': 0, 'cost': -1} MAX_ITER = int(20000) stateStack = Stack() visitedSet = set() actionList = [] # add actions to get to the state, use pop to remove last one successorDict = {} curState = problem.getStartState() stateStack.push(curState) for it in range(MAX_ITER): if problem.isGoalState(curState): return actionList if curState not in visitedSet: successors = problem.getSuccessors(curState) successorDict[curState] = successors visitedSet.add(curState) nStateTuple = filter(lambda x: x[0] not in visitedSet, successorDict[curState]) # get next state if len(nStateTuple) == 0: stateStack.pop() actionList.pop() curState = stateStack.list[-1] else: curState = nStateTuple[0][successor_idx['state']] stateStack.push(curState) actionList.append(nStateTuple[0][successor_idx['dir']]) 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 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 [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() visited = set() path = Stack() start = problem.getStartState() visited.add(start) path.push(start) children = problem.getSuccessors(start) for child in children: fringe.push(child) ds = DFSRec(problem,fringe,visited,path) if ds != None: break pathToGoal = directions(ds) return pathToGoal
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 depthFirstSearch(problem): from collections import defaultdict from util import Stack initial_node=problem.getStartState() current_node=defaultdict(list) current_node[initial_node].append("No parent") current_node[initial_node].append("No direction") stack=Stack() stack.push(current_node) current_node=stack.pop() direction_list={} Child=current_node.keys() Parent=current_node.values()[0] visited_list={} while (problem.isGoalState(Child[0]) is not True): if(Child[0] in visited_list.keys()): current_node=stack.pop() Child=current_node.keys() Parent=current_node.values()[0] else: visited_list[Child[0]]=Parent[0] direction_list[Child[0]]=Parent[1] Successor_node=problem.getSuccessors(Child[0]) for index in range(len(Successor_node)): temp_dict=defaultdict(list) temp_dict[Successor_node[index][0]].append(Child[0]) temp_dict[Successor_node[index][0]].append(Successor_node[index][1]) #print"The temp dict values are",temp_dict stack.push(temp_dict) #print " The heap of queue is",priority_queue.heap current_node=stack.pop() #print "The current node is",current_node Child=current_node.keys() Parent=current_node.values()[0] visited_list[Child[0]]= Parent[0] direction_list[Child[0]]=Parent[1] backtracking =[] path = Child[0] backtracking.append(direction_list[path]) path = visited_list[path] print "The path is",path while (path!= problem.getStartState()): backtracking.append(direction_list[path]) path = visited_list[path] backtracking.reverse() return backtracking util.raiseNotDefined()
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: 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 ***" 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. 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 ***" start = problem.getStartState() from util import Stack fringe = Stack() fringe.push([(start, 'Start', 1)]) result = None while result == None: currentPath = fringe.pop() currentState = currentPath[-1] if problem.isGoalState(currentState[0]): result = currentPath continue succ = problem.getSuccessors(currentState[0]) for state in succ: if state[0] not in map(lambda x: x[0], currentPath): new_list = currentPath[:] new_list.append(state) fringe.push(new_list) steps = [] for state in result[1:]: steps.append(state[1]) return steps
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 dfs2(self, starting_vertex: int, destination_vertex: int) -> List[int]: """ """ stack = Stack() visited = set() stack.push([starting_vertex]) while stack.size() > 0: path = stack.pop() vertex = path[-1] if vertex not in visited: if vertex == destination_vertex: return path else: visited.add(vertex) for next_vert in self.vertices[vertex]: new_path = list(path) new_path.append(next_vert) stack.push(new_path) 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 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 dft(): #Create Stack stack = Stack() #Put the starting point in the stack stack.push(world.starting_room) # Create a set to keep track of where we've been visited = set() #While the stack is not empty while stack.size() > 0: # grabs room instance off of stack room = stack.pop() # Grabbing the specific ID room_id = room.id # If room not in graph if room_id not in graph.vertices: # Add it graph.add_vertex(room_id) # Get an array of available exits(Edges) of that room exits = room.get_exits() # For each exit for direction in exits: # Grab the exits room.id exit_room = room.get_room_in_direction(direction) exit_room_id = exit_room.id # If exit room not in graph, add it if exit_room_id not in graph.vertices: graph.add_vertex(exit_room_id) # Make a connection from initial room to exit. Make note of direction as well graph.add_edge(room_id, exit_room_id, direction) # If we haven't already visited exit room, add it to the stack if exit_room_id not in visited: stack.push(exit_room) visited.add(room_id)
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 next_node:", problem.getSuccessors(problem.getStartState())) """ "*** YOUR CODE HERE IF YOU WANT TO PRACTICE ***" from util import Stack from game import Directions open = Stack() closed = [] open.push((problem.getStartState(), [])) while not open.isEmpty(): current_node, actions = open.pop() # if current state is the goal state # return list of actions if problem.isGoalState(current_node): return actions if current_node not in closed: # expand current node # add current node to closed list expand = problem.getSuccessors(current_node) closed.append(current_node) for location, direction, cost in expand: # if the location has not been visited, put into open list if (location not in closed): open.push((location, actions + [direction])) util.raiseNotDefined()
def findPathToClosestDot(self, gameState): from util import Stack from util import Queue """ Returns a path (a list of actions) to the closest dot, starting from gameState. """ # Here are some useful elements of the startState startPosition = gameState.getPacmanPosition() food = gameState.getFood() walls = gameState.getWalls() problem = AnyFoodSearchProblem(gameState) s = Queue() state = startPosition dict = {} parent = {} temp = [] dict[state] = 'false' while (not (problem.isGoalState(state))): z = problem.getSuccessors(state) for y in z: if (not (y[0] in dict)): dict[y[0]] = 'false' s.push(y) if (temp): parent[y] = temp temp = s.pop() state = temp[0] path = Stack() path.push(temp[1]) while (temp in parent): path.push(parent[temp][1]) temp = parent[temp] # print path.list path.list.reverse() return path.list
def dfs_recursive(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. This should be done using recursion. """ s = Stack() s.push([starting_vertex]) visited = set() # while s.size() > 0: # path = s.pop() # last_vertex = path[-1] # if last_vertex not in visited: # if last_vertex == destination_vertex: # return path # else: # visited.add(last_vertex) # for next_vertex in self.vertices[last_vertex]: # new_path = [*path, next_vertex] # s.push(new_path) def recurse(start, end, stack, visited): if stack.size() > 0: path = stack.pop() last_vertex = path[-1] if last_vertex not in visited: if last_vertex == end: return path else: visited.add(last_vertex) for next_vertex in self.vertices[last_vertex]: new_path = [*path, next_vertex] stack.push(new_path) return recurse(start, end, stack, visited) else: return -1 return recurse(starting_vertex, destination_vertex, s, visited)
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 ***" # initialise a Stack to implement DFS from util import Stack start = problem.getStartState() list = Stack() list.push((start, [])) # mark the current vertex as visited visited, stack = set(), [start] # obtain next vertex to visit until stack is empty while list: vertex = list.pop() print vertex if vertex[0] in visited: continue visited.add(vertex[0]) # exit once Goal is reached and return path followed if problem.isGoalState(vertex[0]): return vertex[1] # obtain valid successors of current vertex and put them in the stack next = problem.getSuccessors(vertex[0]) for successor, newpath, cost in next: list.push((successor, vertex[1] + [newpath]))
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 fringe = Stack() # LIFO closed = [] # add start State fringe.push((problem.getStartState(), [])) while not fringe.isEmpty(): # get current node cur_node, actions = fringe.pop() # if current node is Goal, stop if problem.isGoalState(cur_node): return actions # if current node doesnot happen if cur_node not in closed: expand = problem.getSuccessors(cur_node) closed.append(cur_node) for location, direction, cost in expand: if (location not in closed): fringe.push((location, actions + [direction])) util.raiseNotDefined()
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ # Create an empty stack and push "PATH To The Starting Vertex ID" s = Stack() s.push([starting_vertex]) # Create a set to store visited vertices visited = set() # While the stack is not empty while s.size() > 0: # pop the first PATH path = s.pop() # Grab the last vertex from the PATH last_vertex = path[-1] # Check if the vertex hasn't been visited if last_vertex not in visited: # Is this vertex the target? if last_vertex == destination_vertex: # Return the PATH return path # Mark it as visited visited.add(last_vertex) # Then add a PATH to its neighbors to the back of the stack for neighbor_vertex in self.get_neighbors(last_vertex): # Make a copy of the PATH # Append the neighbor the back of the PATH # push out new PATH s.push(path + [neighbor_vertex]) # return None return None
def DFS(s0, trans, goal): """Performs a depth-first search. Performs a depth-first search starting from state s0 and trying to reach goal state, if it exists. Search also prints out the results if the path is found. Args: s0: String representing the name of the starting state. trans: A dictionary containing list of possible transitions and their costs for each key that represents the state name. goal: A list of goal state names. Returns: A list representing the path from s0 to one of the goal states if the path is found, else returns None """ print('Running dfs:') open = Stack() open.push(Node(s0)) visited = set() while open: n = open.pop() visited.add(n.s) if n.s in goal: path = n.path() print_search_results(path, len(visited)) return path for m, _ in trans.get(n.s, []): if m not in visited: open.push(Node(m, n.d + 1, n)) print('Path not found.') return None
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): """ 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 game import Directions from util import Stack close = set() fringes = Stack() fathers = Stack() solution = [] currentState = (problem.getStartState(), None, 1) fringes.push(currentState) fathers.push(currentState) while (not fringes.isEmpty()): currentState = fringes.pop() father = fathers.pop() new_sol = [] for i in range(0, len(solution)): if (solution[i][0] != father[0]): new_sol.append(solution[i]) else: break new_sol.append(father) solution = new_sol solution.append(currentState) close.add(currentState[0]) if (problem.isGoalState(currentState[0])): ret = [] for i in range(1, len(solution)): ret.append(solution[i][1]) return ret successors_list_temp = problem.getSuccessors(currentState[0]) successors_list = [] for i in range(0, len(successors_list_temp)): if (not successors_list_temp[i][0] in close): successors_list.append(successors_list_temp[i]) if (successors_list): for successor in successors_list: fringes.push(successor) fathers.push(currentState)
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ stack = Stack() visited_vertices = set() # Create an empty set to track visited verticies stack.push({ 'current_vertex': starting_vertex, 'path': [starting_vertex] }) # while the queue is not empty: while stack.size() > 0: # get current vertex PATH (dequeue from queue) current_obj = stack.pop() current_path = current_obj['path'] current_vertex = current_obj['current_vertex'] # set the current vertex to the LAST element of the PATH # Check if the current vertex has not been visited: if current_vertex not in visited_vertices: # CHECK IF THE CURRENT VERTEX IS DESTINATION # IF IT IS, STOP AND RETURN if current_vertex == destination_vertex: return current_path # Mark the current vertex as visited # Add the current vertex to a visited_set visited_vertices.add(current_vertex) for neighbor_vertex in self.get_neighbors(current_vertex): # Queue up NEW paths with each neighbor: new_path = list(current_path) new_path.append(neighbor_vertex) stack.push({ 'current_vertex': neighbor_vertex, 'path': new_path }) 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 ***" #Stack to hold the node that have been visited along with the path taken from the start node to reach that node. stack = Stack() #Set to hold the node explored. explorednode = set() #Get the start node. startnode = problem.getStartState() #Push the starting node on the Stack along with an empty set to know the direction in order to reach the node. stack.push((startnode, [])) #Loop till the stack is empty while stack.isEmpty() is not True: #Pop the currentnode and the direction from the stack currentnode, direction = stack.pop() #We will now add the node to set of explored node. explorednode.add(currentnode) #If the node is the goal. We made it!! if problem.isGoalState(currentnode): #The direction holds the way to reach till the goal from the start node. return direction #Loop for each successor(child) of the current node. for (successor, action, stepCost) in problem.getSuccessors(currentnode): #If the successor(child) is not explored if successor not in explorednode: #Add the successor to the stack along with the path to reach it. stack.push((successor, direction + [action])) util.raiseNotDefined()
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ # # Create an empty stack and push the starting vertex ID # s = Stack() # s.push(starting_vertex) # # Create an empty set to store visited vertices # visited = set() # # While the stack is not empty... # while s.size() > 0: # # Pop the first vertex # v = s.pop() # # If that vertex has not been visited... # if v not in visited: # # Mark it as visited # print(v) # visited.add(v) # # Then add all of its neighbors to the top of the stack # for neigbor in self.vertices[v]: # s.push(neigbor) stack = Stack() stack.push([starting_vertex]) # Enstack a list to use as our path visited = set() while stack.size() > 0: path = stack.pop() vertex = path[-1] if vertex not in visited: if vertex == destination_vertex: return path visited.add(vertex) for next_vertex in self.vertices[vertex]: # Copy path to avoid pass by reference bug new_path = list(path) new_path.append(next_vertex) stack.push(new_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 util import Stack s = Stack() start = problem.getStartState() visited_state = [start] data = [[start], [], 0] s.push(data) while not s.isEmpty(): current = s.pop() current_node = current[0][-1] if problem.isGoalState(current_node): return current[1] for leaf in problem.getSuccessors(current_node): next_state = leaf[0] next_direction = leaf[1] next_cost = leaf[2] if next_state not in visited_state: visited_state.append(next_state) next_states = current[0][:] next_states.append(next_state) next_directions = current[1][:] next_directions.append(next_direction) new_cost = current[2] + next_cost next_data = [next_states, next_directions, new_cost] s.push(next_data) return [] "util.raiseNotDefined()"
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 stack = Stack() # stack of Nodes visited = set() node = Node(problem.getStartState(), None, 0, None) stack.push(node) print(problem.getStartState()) print("Corners:") print(problem.getStartState()) while not stack.isEmpty(): curr = stack.pop() visited.add(curr.state) print(curr.state) if problem.isGoalState(curr.state): print("this is goal state") return path(curr, problem) successors = problem.getSuccessors(curr.state) for s in successors: if s[0] not in visited: newNode = Node(s[0], s[1], s[2], curr) stack.push(newNode)
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 start = problem.getStartState() # init pos with the start state exploredSet = Stack() # use it as the fringe of graph search visited = [] # Visited states path = [] # Every state keeps it's path from the starting state if (problem.isGoalState(start)): return [] exploredSet.push((start, [])) # push start to the stack while (True): if exploredSet.isEmpty(): return [] pos, path = exploredSet.pop() visited.append(pos) # add node to visited list if (problem.isGoalState(pos)): return path successors = problem.getSuccessors(pos) # successor,action, stepCost if successors: for succ in successors: if succ[0] not in visited: # if visited and set doesnt contains succ, add it newPath = path + [succ[1]] exploredSet.push((succ[0], newPath))
def earliest_ancestor(ancestors, starting_node): new_graph = Graph() s = Stack() s.push([starting_node]) visited = set() path = [] for i in ancestors: for j in i: if j not in visited: new_graph.add_vertex(j) visited.add(j) for i in ancestors: new_graph.add_edge(i[1], i[0]) visited = set() while s.size(): p = s.pop() v = p[len(p) - 1] if v not in visited: if len(new_graph.vertices[v]) == 0: path.append(p) visited.add(v) for next_vertex in new_graph.vertices[v]: p_copy = p[:] p_copy.append(next_vertex) s.push(p_copy) longest_path = path[0] for v in path: if len(v) > len(longest_path): longest_path = v if (len(v) == len(longest_path)) and (v[-1] < longest_path[-1]): longest_path = v result = longest_path[-1] if result == starting_node: return -1 else: return result
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 # the component of tree is (state, the path to the state) tree = Stack() tree.push(((problem.getStartState()), [])) # store the visited state visited = [] while (not tree.isEmpty()): (state, path) = tree.pop() if (problem.isGoalState(state)): break successors = problem.getSuccessors(state) for i in successors: if ( i[0] not in visited ): # any state has been visited doesn't need to be visited again visited.append(i[0]) tree.push((i[0], path + [i[1]])) return path util.raiseNotDefined()
def dft(self, starting_vertex): """ Print each vertex in depth-first order beginning from starting_vertex. """ visited = set() # declare a new set to keep track of visits stack = Stack( ) # declare a new stack to keep track of order in which to visit stack.push( starting_vertex ) # push starting index into the stack to start the while loop printable = [] while stack.size() > 0: # while there are vertices in the stack v = stack.pop() # take one off the end if v not in visited: # if it hasn't been visited visited.add(v) # note it's been visited printable.append(v) # do the thing we need to do for neighbor in self.vertices[v]: # loop through its neighbors stack.push(neighbor) # add them to the stack print('dft: ', printable)
def dft(self, starting_vertex_id): # create empty stack push the starting vertex id s = Stack() s.push(starting_vertex_id) # create a set to store our visited vertices visited = set() # while stack is not empty (len greater than 0) while s.size() > 0: # pop the first vertex v = s.pop() # if that vertex has not been visited if v not in visited: # mark as visited and print for debugging visited.add(v) print(v) # for debugging # iterate over the child vertices of the current vertex for next_vertex in self.vertices[v]: # push the next vertex s.push(next_vertex)
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 start = problem.getStartState() frontier = Stack() frontier.push((start, [])) return doDFS([], problem, frontier)
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ path = [] stack = Stack() visited = set() stack.push(starting_vertex) while stack.size() > 0: vertex = stack.pop() if vertex not in visited: visited.add(vertex) path.append(vertex) if vertex == destination_vertex: break for next_vert in self.vertices[vertex]: stack.push(next_vert) return path
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ stack = Stack() stack.push(starting_vertex) traversed = set() path = [] while stack.size() > 0: current = stack.pop() path.append(current) for neighbor in self.get_neighbors(current): if neighbor not in traversed: traversed.add(neighbor) stack.push(neighbor) if neighbor == destination_vertex: path.append(neighbor) return path
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ stack = Stack() stack.push([starting_vertex]) visited = set() while stack.size() > 0: path = stack.pop() vertex = path[-1] if vertex not in visited: if vertex == destination_vertex: return path visited.add(vertex) for next_vert in self.get_neighbors(vertex): new_path = list(path) new_path.append(next_vert) stack.push(new_path)
def dft(self, starting_vertex): """ Print each vertex in depth-first order beginning from starting_vertex. """ # Same as above, but using a stack...! to_visit = Stack() to_visit.push(starting_vertex) visited = set() while to_visit.size() > 0: current_vertex = to_visit.pop() if current_vertex not in visited: visited.add(current_vertex) print(current_vertex) for child_vertex in self.vertices[current_vertex]: to_visit.push(child_vertex)
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ # TODO stack = Stack() stack.push(starting_vertex) paths = dict() paths[starting_vertex] = [starting_vertex] while stack.size() > 0: current_vertex = stack.pop() for vertex in self.get_neighbors(current_vertex): current_path = paths[current_vertex] + [vertex] if vertex in paths and len(current_path) < len(paths[vertex]) or vertex not in paths: paths[vertex] = current_path stack.push(vertex) return paths[destination_vertex]
def dft(self, starting_vertex): """ Print each vertex in depth-first order beginning from starting_vertex. """ s = Stack() s.push(starting_vertex) visited = set() while s.size() > 0: v = s.pop() if v not in visited: print(v) visited.add(v) for next_vert in self.get_neighbors(v): s.push(next_vert)
def dfs(self, starting_vertex, destination_vertex): """ Return a list containing a path from starting_vertex to destination_vertex in depth-first order. """ s = Stack() s.push([starting_vertex]) visited = set() while s.size() > 0: path = s.pop() v = path[-1] while v not in visited: if v == destination_vertex: return path visited.add(v) for neighbor in self.vertices[v]: path_copy = path.copy() path_copy.append(neighbor) s.push(path_copy)
def dft(self, starting_vertex): """ Print each vertex in depth-first order beginning from starting_vertex. """ stack = Stack() stack.push(starting_vertex) visited = set() while stack.size() > 0: current_node = stack.pop() if current_node not in visited: print(current_node) visited.add(current_node) neighbors = self.get_neighbors(current_node) for neighbor in neighbors: stack.push(neighbor)
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: 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 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