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()
    visitedNodes = []
    actions = []
    fringe = util.Stack()
    cost = 0
    if (problem.isGoalState(startState) == True
        ):  #if startState is the goalState
        return actions
    else:
        # Data Type Format : (currentState,actions,cost) based on errors I got :\
        fringe.push((startState, actions, cost))
        while (fringe.isEmpty() == False):
            currentState, actions, cost = fringe.pop()
            if (problem.isGoalState(currentState)):
                return actions

            elif ((currentState in visitedNodes) == False):
                visitedNodes.append(currentState)
                currentNodeSuccessors = problem.getSuccessors(currentState)
                for node in currentNodeSuccessors:
                    state, action, cost = node
                    if ((state in visitedNodes) == False):
                        newNode = (state, actions + [action], cost)
                        fringe.push(newNode)

    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 = util.Stack()
    visited = []
    start_node = (problem.getStartState(), [])

    if problem.isGoalState(start_node):
        return []
    stack.push(start_node)

    while not stack.isEmpty():
        top = stack.pop()
        location = top[0]
        path = top[1]

        if location not in visited:
            visited.append(location)
            if problem.isGoalState(location):
                return path
            successors = problem.getSuccessors(location)
            if successors:
                for element in successors:
                    if element[0] not in visited:
                        new_path = path + [element[1]]
                        stack.push((element[0], new_path))
    return []
示例#3
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())
    """

    frontier = util.Stack()
    visited = {}

    frontier.push(BSTNode((problem.getStartState(), 'Start', 0), None, []))

    while not frontier.isEmpty():
        current = frontier.pop()

        if problem.isGoalState(current.node[0]):
            directions = []

            while current.node[1] != 'Start':
                directions.append(current.node[1])
                current = current.parent

            directions = directions[::-1]
            return directions

        if not current.node[0] in visited:
            visited[current.node[0]] = current

            for successor in problem.getSuccessors(current.node[0]):
                successor = BSTNode(successor, current, [])
                if not successor.node[0] in visited:
                    frontier.push(successor)
                    current.children.append(successor)
示例#4
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 ***"
    visit = []
    actions = []
    stack = util.Stack()

    begin_state = problem.getStartState()
    stack.push((begin_state, actions))

    while not stack.isEmpty():
        current_state, current_action = stack.pop()

        # Break if hit the goal state
        if problem.isGoalState(current_state):
            res = current_action
            break

        # Find all adjacents and push them into stack
        if current_state not in visit:
            visit.append(current_state)
            successors = problem.getSuccessors(current_state)
            for successor in successors:
                adjacent, action, _ = successor
                path = current_action + [action]
                stack.push((adjacent, path))
    return res
    # print(res)
    util.raiseNotDefined()
示例#5
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 ***"

    closedSet = set()
    dataStructure = util.Stack()
    path = []

    pathTuple = ()
    if "startState" in dir(problem):
        nodeCoordStartState = problem.startState
        pathTuple = ((nodeCoordStartState, "", 0), )
    elif "getStartState" in dir(problem):
        nodeCoordStartState = problem.getStartState()
        pathTuple = ((nodeCoordStartState, "", 0), )
    else:
        raise Exception("No recognizable function for getting the Start State")

    dataStructure.push(pathTuple)

    result = findSolution(problem, pathTuple, dataStructure, closedSet)

    if result is None:
        raise Exception("No solution exists!")

    path = getListOfActions(result)
    #print "[Final Path] [%s] with length %d" % (str(result), len(result))
    #print "Path: %s with length %d" % (str(path), len(path))
    return path
示例#6
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())

    print "Start:", problem.getStartState()
    print "Is the start a goal?", problem.isGoalState(problem.getStartState())
    childs = problem.getSuccessors(problem.getStartState())
    print "Start's successors:", childs
    firstChild = childs[0]
    print "second successors:", problem.getSuccessors(firstChild[0])
    """
    "*** YOUR CODE HERE ***"
    "Initiate primary variables"
    stack = util.Stack()
    current_position = problem.getStartState()
    visited = []
    route = []
    stack.push((current_position, route))

    while not stack.isEmpty() and not problem.isGoalState(current_position):
        state, actions = stack.pop()
        visited.append(state)
        children = problem.getSuccessors(state)
        for child in children:
            coordinates = child[0]
            if not coordinates in visited:
                current_position = coordinates
                direction = child[1]
                stack.push((coordinates, actions + [direction]))
    return actions + [direction]
    util.raiseNotDefined()
示例#7
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 ***"
    start = problem.getStartState()
    # print start;
    stack = util.Stack()
    visited = []
    stack.push((start, []))
    # print "Added to stack: ", start;
    while not stack.isEmpty():
        currentNode, path = stack.pop()
        # print "Removed from stack ",currentNode;
        # print "path followng: ", path;
        #print currentNode,path
        #print currentNode,path,cost;
        if (problem.isGoalState(currentNode)):
            return path
        if (currentNode not in visited):
            visited.append(currentNode)
            # print "visited ",visited;
            for nextNode, nextPath, cost in problem.getSuccessors(currentNode):
                #cost not needed for dfs...ignore for now
                # print "nextNode", nextNode;
                if (nextNode not in visited):
                    #print "path, nextpath",path,nextPath;
                    stack.push((nextNode, path + [nextPath]))
                #  print "Added to Stack: ",nextNode;

    util.raiseNotDefined()
示例#8
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    isGoal = 0  #boolean-like item specifically for breaking the while loop once the goal is found
    p = []  #Holder for the final
    start = problem.getStartState()  #obtaining the start
    current = util.Queue()
    current.push((start, []))  #A variable for the current state
    ar = [start
          ]  #Set of all values checked specifically in the coordinates form
    c = util.Stack()  #Holder for the order of directions
    layer = 0

    #While loop to loop through the ways to go until we have the end
    while isGoal == 0:
        eck = set(
            ar
        )  #Putting the already chose values in a set so I can do "if _ in ar" without a loop
        reg = current.pop()
        wq = problem.isGoalState(reg[0])
        if wq == 1:  #Checks if we are in the goal state
            isGoal = 1  #sets so we can break the loop
            p = reg[1]

        #If it is not the goal node
        else:
            succ = problem.getSuccessors(
                reg[0])  #Get the successors from the current node

            #For loop to go through the successors and add them to the queue
            for i in range(0, len(succ)):
                ree = reg[1]  #Holder for the current list of nodes visited
                if succ[i][
                        0] in eck:  #Checks if we have already been through this node
                    layer = layer  #Placeholder line so it will not do the stuff to get added
                else:  #If not already checked
                    w = succ[i][0]  #Puts a variable w to be the coordinate
                    current.push((w, ree + [succ[i][1]]))
                    ar.append(
                        succ[i][0]
                    )  #Adds the coordinates to the checked coordinates list
    return p  #Returns the list of directions
示例#9
0
def graph_search_astar(problem, fringe):
    """Search through the successors of a problem to find a goal.
    The argument fringe should be an empty queue.
    If two paths reach a state, only use the best one. [Fig. 3.18]"""
    closed = {}
    path = []
    parentMap = {}
    flipper = util.Stack()
    startofpac = problem.getStartState()
    for element in problem.getSuccessors(problem.getStartState()):
        fringe.push(element, 1)
        state, direction, cost = element
        parentMap[element] = problem.getStartState()
    while fringe:
        parent = fringe.pop()
        parent_state, direction, cost = parent
        print "parent:", parent
        if problem.isGoalState(parent_state):
            curr = parent
            previous = None
            while (curr in parentMap.keys()):
                flipper.push(curr)
                curr = parentMap[curr]
                previous = curr
            while not flipper.isEmpty():
                state, direction, cost = flipper.pop()
                path.append(direction)
            return path
        if parent not in closed:
            closed[parent] = True
            children = problem.getSuccessors(parent_state)
            for child in children:
                fringe.push(child,
                            util.manhattanDistance(child[0], (1, 1)) +
                            util.manhattanDistance(parent[0], startofpac)
                            )  #903-->big..304->med..345-->open..15->tiny
                if child not in parentMap:
                    parentMap[child] = parent
                    print child

    return None
示例#10
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 ***"
    #util.raiseNotDefined()

    ##    print "Start:", problem.getStartState()
    ##    print "Is the start a goal?", problem.isGoalState(problem.getStartState())
    ##    print "Start's successors:", problem.getSuccessors(problem.getStartState())

    explored = []
    frontier = util.Stack()
    frontier.push((problem.getStartState(), []))

    if problem.isGoalState(problem.getStartState()):
        return ['Stop']

    while not frontier.isEmpty():
        state = frontier.pop()
        if state[0] not in explored:
            explored.append(state[0])

            if problem.isGoalState(state[0]):
                return state[1]

            for child in problem.getSuccessors(state[0]):
                if child[0] not in explored:
                    frontier.push((child[0], state[1] + [child[1]]))

    return False
示例#11
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 ***"


  # Initialization
  search_stack = util.Stack()
  traversed = []
  initial_state = problem.getStartState()

  # Push the starting state in the stack.
  search_stack.push((initial_state, []))

  # While search_stack in the fringe of the present state is not empty, go on searching the goal.
  while search_stack:
      (state, move_dir) = search_stack.pop()

      if not state in traversed:  # Avoid revisiting the same state.
          traversed.append(state)

          if problem.isGoalState(state):
              return move_dir  # Return move_dir if goal is searched.

          children = problem.getSuccessors(state)  # Get all child nodes of this state.

          for child in children:  # child[0]: state of child, child[1]: action to get to the child.
              search_stack.push((child[0], move_dir + [child[1]]))

  return []  # Goal does not exist in the search_stack.
示例#12
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())
     util.raiseNotDefined()
    """
    "*** YOUR CODE HERE ***"
    openList = util.Stack()
    closed = []
    tracker = {}
    metadata = ((None, None, None), problem.getStartState())
    currentstate = (problem.getStartState(), metadata)
    while not problem.isGoalState(currentstate[0]):
        parentstate = currentstate[0]
        if parentstate not in closed:
            closed.append(parentstate)
            tracker[parentstate] = (currentstate[1][1], currentstate[1][0][1])
            for successors in problem.getSuccessors(parentstate):
                if successors not in closed:
                    metadata = (successors, parentstate)
                    openList.push((successors[0], metadata))
        currentstate = openList.pop()
    tracker[currentstate[0]] = (currentstate[1][1], currentstate[1][0][1])
    returnPath = []
    state = currentstate[0]
    while state != problem.getStartState():
        movement = tracker[state][1]
        returnPath.append(movement)
        state = tracker[state][0]

    returnPath.reverse()
    return returnPath
示例#13
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())
    """
    initialPath = []
    initialState = problem.getStartState()
    initialCost = 0
    myNode = Node(initialPath, initialState, initialCost)
    if problem.isGoalState(myNode.getState()):
        return myNode.getPath()
    frontier = util.Stack()
    frontier.push(myNode)
    exploredSet = set([])
    
    while 1:
        if frontier.isEmpty():
            return []
        node = frontier.pop()
        if problem.isGoalState(node.getState()):
            return node.getPath()
        exploredSet.add(node.getState())
        for triple in problem.getSuccessors(node.getState()):
            action = triple[1]
            state = triple[0]
            cost = triple[2]
            path = (list)(node.getPath())
            path.append(action)
            child = Node(path, state, cost)
            if child.getState() not in exploredSet:
                frontier.push(child)
    util.raiseNotDefined()
示例#14
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 ***"
    import game
    succes = []
    sucstack = util.Stack()
    hf = problem.getStartState()
    succ = (hf, 'Stop', 0)
    while (True):
        if (succ == 'return'):
            succes.pop()
        else:
            succes.append(succ)
            if (problem.isGoalState(succ[0])): break
            sucstack.push('return')
            for ss in problem.getSuccessors(succ[0]):
                flag = True
                for i in range(len(succes), 0, -1):
                    if (ss[0] == succes[i - 1][0]):
                        flag = False
                        break
                if (flag): sucstack.push(ss)
        if (sucstack.isEmpty()): break
        succ = sucstack.pop()

    actions = []
    for s in succes:
        actions.append(s[1])
    return actions[1:]
示例#15
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 ***"
    front = util.Stack()
    visited = list()
    pred = dict()  # {successor: (predecessor, action)}
    goal = None
    front.push(problem.getStartState())
    while not front.isEmpty():
        node = front.pop()
        if problem.isGoalState(node):
            goal = node
            break
        visited.append(node)
        for succ in problem.getSuccessors(node):
            # successor is a tuple (nextState, action, cost)
            if succ[0] not in visited:
                front.push(succ[0])
                pred[succ[0]] = (node, succ[1])

    # backtrack to get the actions
    actions = []
    if goal != None:
        node = goal
        while node != problem.getStartState():
            actions.insert(0, pred[node][1])
            node = pred[node][0]

    return actions
示例#16
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:
    """

    nodeInit = Node(problem=problem, stateCurrent=problem.getStartState())

    if problem.isGoalState(nodeInit.nodeGetCurrentState()):

        return Solution(nodeInit)

    frontier = util.Stack()
    frontier.push(nodeInit)

    explored = set()

    while frontier.isEmpty() != True:

        currentNode = frontier.pop()
        if problem.isGoalState(currentNode.nodeGetCurrentState()):
            return Solution(currentNode)
        if currentNode.nodeGetCurrentState() not in explored:
            explored.add(currentNode.nodeGetCurrentState())

            for successor in problem.getSuccessors(
                    currentNode.nodeGetCurrentState()):

                childNode = Node(problem=problem,
                                 stateCurrent=successor[0],
                                 nodePrev=currentNode,
                                 action=successor[1])

                if childNode.nodeGetCurrentState() not in explored:

                    frontier.push(childNode)

    return None
示例#17
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())
    """
    # We use Position Search problem instance. It's getSuccessors method returns state, action and cost.
    # Stack has LIFO. list.pop() pops the last element inserted into it.
    fringe = util.Stack()
    # A set to keep track of nodes visited.
    # Set() avoids duplicates thus abiding to principle of not visiting a node more than once in Graph search.
    nodes_expanded = set()
    # For DFS cost does not matter so we pass it as 1.
    # We initially push start state co-ordinates and empty list of directions onto stack.
    fringe.push((problem.getStartState(), [], 0))
    # The loop executes until all the nodes are popped off the fringe.
    while not fringe.isEmpty():
        state, actions, cost = fringe.pop()
        # We check if the dequeued(popped) node's state is equal to goal state.(Goal test).
        # If True we return the list of actions for the pacman to reach its goal state.
        if problem.isGoalState(state):
            return actions
        # If the node is already visited we do not push its successors onto fringe thus we avoid cycles in graph search.
        if state in nodes_expanded:
            continue
        # If the node is not visited we mark it as visited and we push its successors onto the fringe.
        nodes_expanded.add(state)
        for successor_state, successor_action, step_cost in problem.getSuccessors(
                state):
            fringe.push(
                (successor_state, actions + [successor_action], step_cost))
    # Added as defensive mechanism.
    return []
示例#18
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    # initialization
    state = problem.getStartState()
    visit = []
    visit.append(state)
    road = []
    unvisit = util.Queue()
    ans=util.Stack()
    end=[]
    # until meet goal
    while problem.isGoalState(state) != True:
        action = problem.getSuccessors(state)
        # memory unvisit points
        if len(action) > 0:
            for k in range(0, len(action)):
                unvisit.push([action[k][0], action[k][1], state]) #[now,path,parent]

        temp = unvisit.pop()

        # avoid walking backward
        while temp[0] in visit and problem.isGoalState(state) != True:
            temp = unvisit.pop()

        state=temp[0]
        road.append([temp[0],temp[1],temp[2]])
        visit.append(state)

    # get one road
    k=road.pop()
    ans.push(k[1])
    for n in range(len(road)):
        p=road.pop()
        if k[2]==p[0]:
            ans.push(p[1])
            k=p
    while ans.isEmpty()!=True:
        end.append(ans.pop())

    return end
示例#19
0
def depthFirstSearch(problem):
    stack = util.Stack()
    stack.push([(problem.getStartState(), "Stop", 0)])
    visited_nodes = []

    while not stack.isEmpty():
        path = stack.pop()
        current_state = path[-1][0]

        if problem.isGoalState(current_state):
            return [x[1] for x in path][1:]

        if current_state not in visited_nodes:
            visited_nodes.append(current_state)

            for next_node in problem.getSuccessors(current_state):
                next_node_path = path[:]
                next_node_path.append(next_node)
                stack.push(next_node_path)

    return False
示例#20
0
 def dfsMap(self, gameState, startState):
     searchProblem = PositionSearchProblem(gameState=gameState,
                                           startState=startState)
     startState = searchProblem.getStartState()
     stack = util.Stack()
     stack.push((startState, []))
     closed = set()
     while not stack.isEmpty():
         state, path = stack.pop()
         if state not in closed:
             closed.add(state)
             successors = searchProblem.getSuccessors(state)
             self.mapBySuccessor(gameState, state, successors)
             for s, a, c in successors:
                 p = list(path)
                 p.append(state)
                 if s in closed and state != startState:
                     if p[-2] != s:
                         self.mapByVisited(s, p)
                 else:
                     stack.push((s, p))
示例#21
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 ***"
    fringe = util.Stack()

    def addFringe(fringe, state, cost):
        fringe.push(state)

    return genericSearch(problem, fringe, addFringe)
示例#22
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 ***"
    frontier = util.Stack()  # Initialize the stack.
    closed = set(
    )  # Initialize a visited set that contain the visited nodes during traversal.
    start = problem.getStartState()  # Get the start state of agent.
    frontier.push((start, []))  # push the start state into the stack.
    return execute_common_search_logic(frontier, closed, problem)
示例#23
0
def generalSearch(problem, fn):
    dataStructure = {'bfs': util.Queue(), 'dfs': util.Stack()}
    root = problem.getStartState()
    try:
        visited = set()
        fringe = dataStructure[fn]
        fringe.push((root, [], 0))
        while not fringe.isEmpty():
            location, path, cost = fringe.pop()
            if problem.isGoalState(location):
                # print path
                return path
            if location not in visited:
                visited.add(location)
                for x, y, z in problem.getSuccessors(location):
                    if x not in visited:
                        fringe.push((x, path + [y], z))
        return []
    except Exception as e:
        print e
        return []
def 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())
"""
    path ,exploredState,exploredPath =[],[],util.Stack()
    exploredState.append(problem.getStartState())
    exploredPath,isGoal = dfsExplore(problem.getStartState(),exploredState,exploredPath,problem)
    while not exploredPath.isEmpty():
        candidateAction = exploredPath.pop()
        if candidateAction: path.insert(0, candidateAction)
    return path
示例#25
0
def depth_first_search(game, variable_selection, heuristic):
    """
    Search the shallowest nodes in the search tree first.
    """
    explored = set()
    stack = util.Stack()
    stack.push(game.get_initial_board())

    while not stack.isEmpty():
        current_board = stack.pop()
        yield current_board

        if game.is_goal_state():
            yield current_board

        successor = get_successors(current_board)
        for next_board, next_path in successor:
            if next_board not in explored:
                stack.push(next_board)

        explored.add(current_board)
示例#26
0
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 "Start:", problem.getStartState()
    #print "Is the start a goal?", problem.isGoalState(problem.getStartState())
    #print "Start's successors:", problem.getSuccessors(problem.getStartState())
    return graph_search(problem, util.Stack(), add_to_fringe_fn)
示例#27
0
def depthFirstSearch(problem):

    start = problem.getStartState()
    c = problem.getStartState()
    exploredState = []
    exploredState.append(start)
    states = util.Stack()
    stateTuple = (start, [])
    states.push(stateTuple)
    while not states.isEmpty() and not problem.isGoalState(c):
        state, actions = states.pop()
        exploredState.append(state)
        successor = problem.getSuccessors(state)
        for i in successor:
            coordinates = i[0]
            if not coordinates in exploredState:
                c = i[0]
                direction = i[1]
                states.push((coordinates, actions + [direction]))
    return actions + [direction]
    util.raiseNotDefined()
示例#28
0
文件: search.py 项目: hyzale/pacman
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 ***"

    # initialize the fringe and expanded list
    fringe = util.Stack()
    return searchHelper(problem, fringe)

    "util.raiseNotDefined()"
示例#29
0
def DFSLimited(problem, limit=70):

    nodo = problem.getStartState()
    frontera = util.Stack()
    frontera.push((nodo, [], 0))
    cerrados = []

    while (not frontera.isEmpty()):

        nodo, list_position, coste = frontera.pop()

        if (problem.isGoalState(nodo)):
            print(len(list_position))
            return list_position

        if (nodo not in cerrados and coste < 75):
            cerrados.append(nodo)
            for success in problem.getSuccessors(nodo):
                if (success[0] not in cerrados):
                    frontera.push((success[0], list_position + [success[1]],
                                   coste + success[2]))
示例#30
0
def depthFirstSearch(problem):
    """Search the deepest nodes in the search tree first."""

    #init
    closed = set()
    open = util.Stack()
    open.push((problem.getStartState(), []))

    while not open.isEmpty():
        state, actions = open.pop()
        if state in closed:
            continue

        if problem.isGoalState(state):
            print(actions)
            return actions
        closed.add(state)

        for successor, action, g in problem.getSuccessors(state):
            if successor not in closed:
                open.push((successor, actions + [action]))