예제 #1
0
파일: graph.py 프로젝트: dsnair/CS-graphs
    def bfs(self, starting_vertex, destination_vertex):
        q = Queue()
        visited = []
        q.enqueue([starting_vertex])

        while q.size():
            path = q.dequeue()
            # print("Path", path)
            vertex = path[-1]

            if vertex not in visited:
                if vertex == destination_vertex:
                    return path

                visited.append(vertex)

                for next_vertex in self.vertices[vertex]:
                    new_path = list(path)
                    new_path.append(next_vertex)
                    q.enqueue(new_path)

        return None
예제 #2
0
def solution(s):
    q = Queue(len(s))
    for token in s:
        if token in '{[(':
            q.put(token)
        else:
            if q.empty():
                return 0
            if token == ')':
                if q.get() != '(':
                    return 0
            elif token == '}':
                if q.get() != '{':
                    return 0
            else:
                if q.get() != '[':
                    return 0

    if q.empty():
        return 1
    else:
        return 0
예제 #3
0
파일: social.py 프로젝트: MicahJank/Graphs
    def get_all_social_paths(self, user_id):
        """
        Takes a user's user_id as an argument

        Returns a dictionary containing every user in that user's
        extended network with the shortest friendship path between them.

        The key is the friend's ID and the value is the path.
        """
        # if the user we are searching its connections - has no friends then we can just return and print a message
        if self.get_friends(user_id) is None:
            print("You have no friends!")
            return

        visited = {}  # Note that this is a dictionary, not a set
        # since i am trying to find a shortest path i will use a BFT
        # visited is a dict that will have the visited user as the key
        # what would the value of the visited user be? - the friends of that user?

        q = Queue()
        path = [user_id]
        q.enqueue(path)

        while q.size() > 0:
            current_path = q.dequeue()
            current_node = current_path[-1]

            if current_node not in visited:
                visited[current_node] = current_path

                if self.get_friends(current_node) is not None:
                    friends = self.get_friends(current_node)

                    for friend in friends:
                        new_path = current_path.copy()
                        new_path.append(friend)
                        q.enqueue(new_path)

        return visited
예제 #4
0
    def bft(self, starting_vertex):
        """
        Print each vertex in breadth-first order
        beginning from starting_vertex.
        """

        # initialize queue with starting vertex
        q = Queue()
        q.enqueue(starting_vertex)

        # set to keep track of vertexes already seen
        visited = set()

        # while queue is not empty if we haven't seen the element frome the
        # queue, add to visited, print, and add neighbors to queue
        while q.size() > 0:
            vertex = q.dequeue()
            if vertex not in visited:
                visited.add(vertex)
                print(vertex)
                for edge in self.get_neighbors(vertex):
                    q.enqueue(edge)
예제 #5
0
파일: graph.py 프로젝트: reeceap124/Graphs
 def bft(self, starting_vertex):
     """
     Print each vertex in breadth-first order
     beginning from starting_vertex.
     """
     #use a queue
     #visited hash table
     #stop when queue is empty
     #add to queue (if not in visited)
     #queue all neighbors
     #dequeue, and add to visited
     visited = set()
     btf_queue = Queue()
     btf_queue.enqueue(starting_vertex)
     while btf_queue.size() > 0:
         print(btf_queue.queue[0])
         neighbors = self.get_neighbors(btf_queue.queue[0])
         visited.add(btf_queue.queue[0])
         btf_queue.dequeue()
         for neighbor in neighbors:
             if neighbor not in visited:
                 btf_queue.enqueue(neighbor)
예제 #6
0
파일: graph.py 프로젝트: nobioma1/Graphs
    def bfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing the shortest path from
        starting_vertex to destination_vertex in
        breath-first order.
        """
        # create set to hold visited vertex
        visited = set()

        # Initialize queue
        queue = Queue()

        # enqueue starting_vertex in a list
        queue.enqueue([starting_vertex])

        # while there is path in queue
        while queue.size():
            # dequeue path
            path = queue.dequeue()

            # get the last vertex in the dequeued path
            last_vertex = path[-1]

            # if last vertex is not already visited
            if last_vertex not in visited:
                # loop through the neighbors of the last_vertex
                for neighbor in self.vertices[last_vertex]:
                    # create new path list
                    new_path = list(path)
                    # append all the neighbors of current vertex to list
                    new_path.append(neighbor)
                    # check if the current neighbor is the destination
                    if neighbor == destination_vertex:
                        # return the new path
                        return new_path
                    # enqueue the new path
                    queue.enqueue(new_path)
                # add the last vertex to visited
                visited.add(last_vertex)
예제 #7
0
    def get_all_social_paths(self, user_id):
        """
        Takes a user's user_id as an argument

        Returns a dictionary containing every user in that user's
        extended network with the shortest friendship path between them.

        The key is the friend's ID and the value is the path.
        """
        q = Queue()
        #Return extended network of users 
        visited = {}  # Note that this is a dictionary, not a set
        # Dictionary will have a key and value pair 
        # !!!! IMPLEMENT ME
        q.enqueue([user_id])
        # For every user_id we need to traverse and find connecting nodes
        # for each node find the shortest path 
        # counter = 0
        while q.size() > 0:
            # counter += 1
            # print("Degree",counter)
            path = q.dequeue()
            # print(path)
            v = path[-1]
            if v not in visited:
                # print(v)
                visited[v] = path
                for friend_id in self.friendships[v]:
                    path_copy = path.copy()
                    path_copy.append(friend_id)
                    q.enqueue(path_copy)
                    
                
        # set the shortest path as the value in key value 
        # Track visited 
        # If not visited ...
            #run our bft for shortest path 

        return visited
예제 #8
0
 def bft(self, starting_vertex):
     """
     Print each vertex in breadth-first order
     beginning from starting_vertex.
     """
     # Create an empty queue and enqueue the starting vertex ID
     q = Queue()
     q.enqueue(starting_vertex)
     # Create an empty Set to store visited vertices
     visited = set()
     # While the queue is not empty...
     while q.size() > 0:
         # De-queue the first vertex
         v = q.dequeue()  # from class in util.py
         # If the 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 back of queue
             for next_vert in self.get_neighbors(v):
                 q.enqueue(next_vert)
예제 #9
0
 def bfs(self, starting_vertex, destination_vertex):
     """
     Return a list containing the shortest path from
     starting_vertex to destination_vertex in
     breath-first order.
     """
     #TODO
     q = Queue()
     q.enqueue([starting_vertex])
     visited = set()
     while q.size() > 0:
         path = q.dequeue()
         vert = path[-1]
         if vert not in visited:
             if vert == destination_vertex:
                 return path
             visited.add(vert)
             for next_vert in self.get_neighbors(vert):
                 path_copy = list(path)
                 path_copy.append(next_vert)
                 q.enqueue(path_copy)
     return None
예제 #10
0
 def bft(self, starting_vertex):
     """
     Print each vertex in breadth-first order
     beginning from starting_vertex.
     """
     # create empty queue and enqueue
     q = Queue()
     q.enqueue(starting_vertex)
     # create a set to store visited vertices
     visited = set()
     # while the queue isn't empty
     if q.size() > 0:
         # dequeue the first vertex
         v = q.dequeue()
         # if that vertex hasn't been visited
         if v not in visited:
             # mark it as visited
             print(v)
             visited.add(v)
             # add all of its neighbors to the back of the queue
             for neighbor in self.vertices[v]:
                 q.enqueue(neighbor)
예제 #11
0
파일: graph.py 프로젝트: bfeole/Graphs
 def bft(self, starting_vertex):
     """
     Print each vertex in breadth-first order
     beginning from starting_vertex.
     """
     # Create an empty queue and enqueue the starting vertex ID
     q = Queue()
     q.enqueue(starting_vertex)
     # Create an empty Set to store visited vertices
     visited = set()
     # While the queue is not empty
     while q.size() > 0:
         # Dequeue the first vertex
         v = q.dequeue()
         # If that vertex has not been visited
         if v not in visited:
             # Mark it as visisted adding it to visited(we're just printing here can be anything)
             # print(v)
             visited.add(v)
             # Then add all of its neighbors to the back of the queue
             for neighbor in self.vertices[v]:
                 q.enqueue(neighbor)
예제 #12
0
def bft(destination):
    q = Queue()
    q.enqueue([(player.current_room,None)])
    newly_visited = set()
    newly_visited.add(player.current_room)
    while q.size() > 0:
        path = q.dequeue()
        current = path[-1][0]
        if current == destination:
            break
        neighbors = get_neighbors(current)
        neighbors = list(neighbors).sort(reverse=True)
        for direction,next_room in neighbors:
            if next_room not in newly_visited:
                new_path = path + [(next_room,direction)]
                q.enqueue(new_path)
                newly_visited.add(next_room)

    for i in range(1,len(path)):
        player.travel(path[i][1])
        traversal_path.append(path[i][1])
        visited.add(path[i][0])
예제 #13
0
파일: social.py 프로젝트: ruihildt/Graphs
    def getAllSocialPaths(self, userID):
        """
        Takes a user's userID as an argument

        Returns a dictionary containing every user in that user's
        extended network with the shortest friendship path between them.

        The key is the friend's ID and the value is the path.
        """
        q = Queue()
        q.enqueue(userID)
        visited = {}

        while q.size() > 0:
            node = q.dequeue()

            for user in self.friendships[node]:
                if user not in visited:
                    visited[user] = self.bfs(user, userID)
                    q.enqueue(user)

        return visited
예제 #14
0
    def get_all_social_paths(self, user_id):
        """
        Takes a user's user_id as an argument

        Returns a dictionary containing every user in that user's
        extended network with the shortest friendship path between them.

        The key is the friend's ID and the value is the path.
        """
        q = Queue()
        q.enqueue([user_id])
        visited = {}  # Note that this is a dictionary, not a set
        while q.size() > 0:
            path = q.dequeue()
            u = path[-1]
            if u not in visited:
                visited[u] = path
                for friend in self.friendships[u]:
                    path_copy = path.copy()
                    path_copy.append(friend)
                    q.enqueue(path_copy)
        return visited
예제 #15
0
파일: graph.py 프로젝트: NikuX/Graphs
 def bft(self, starting_vertex):
     """
     Print each vertex in breadth-first order
     beginning from starting_vertex.
     """
     # create an empty queue and enqueue the starting vertex ID
     q = Queue()
     q.enqueue(starting_vertex)
     # create an empty Set to store visited vertices
     visited = set()
     # while the queue is not empty...
     while q.size() > 0:
         # dequeue the first vertex
         v = q.dequeue()
         # 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 back of the queue
             for neighbor in self.get_neighbors(v):
                 q.enqueue(neighbor)
예제 #16
0
def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    from util import Queue

    visited, fringe = [], Queue()

    fringe.push((problem.getStartState(), ()))
    while fringe.isEmpty() is False:
        curr_state = fringe.pop()

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

        if curr_state[0] not in visited:
            visited.append(curr_state[0])

            for successor in problem.getSuccessors(curr_state[0]):
                added_path = curr_state[1] + (successor[1], )  #adding tuples

                if successor[0] not in visited:
                    fringe.push((successor[0], added_path))
예제 #17
0
파일: graph.py 프로젝트: jtkernan7/Graphs
 def bft(self, starting_vertex):
     """
     Print each vertex in breadth-first order
     beginning from starting_vertex.
     """
     # create empty queue and enqueue starting vertex Id
     q = Queue()
     q.enqueue(starting_vertex)
     # create set to store for visited vertices
     visited = set()
     # while queue not empty
     while q.size() > 0:
         # deque first vertex
         v = q.dequeue()
         # if vertex has not been visited
         if v not in visited:
             # mark as visited
             print(v)
             visited.add(v)
             # add all neighbors to back of queue
             for neighbor in self.vertices[v]:
                 q.enqueue(neighbor)
예제 #18
0
    def bfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing the shortest path from
        starting_vertex to destination_vertex in
        breath-first order.
        """
        q = Queue()
        q.enqueue([starting_vertex])
        visited = set()

        while q.size() > 0:
            path = q.dequeue()
            last_item = path[-1]

            if last_item not in visited:
                visited.add(last_item)

                if last_item is destination_vertex:
                    return path

                for neighbor in self.get_neighbors(last_item):
                    q.enqueue([*path, neighbor])
예제 #19
0
파일: social.py 프로젝트: McNultyPT/Graphs
    def getAllSocialPaths(self, userID):
        """
        Takes a user's userID as an argument

        Returns a dictionary containing every user in that user's
        extended network with the shortest friendship path between them.

        The key is the friend's ID and the value is the path.
        """
        visited = {}  # Note that this is a dictionary, not a set
        queue = Queue()
        queue.enqueue([userID])
        while queue.size() > 0:
            path = queue.dequeue()
            vertex = path[-1]
            if vertex not in visited:
                visited[vertex] = path
                for friendship in self.friendships[vertex]:
                    new_path = list(path)
                    new_path.append(friendship)
                    queue.enqueue(new_path)
        return visited
예제 #20
0
def breadthFirstSearch(problem):
    """
    Search the shallowest nodes in the search tree first.
    """
    "*** YOUR CODE HERE ***"
    from util import Queue

    start = problem.getStartState()
    visited = set()
    queue = Queue()
    queue.push((start, []))

    while not queue.isEmpty():
        current, actions = queue.pop()
        if problem.isGoalState(current):
            return actions
        elif current in visited:
            continue
        visited.add(current)
        for successor in problem.getSuccessors(current):
            if successor[0] not in visited:
                queue.push((successor[0], actions + [successor[1]]))
예제 #21
0
    def bfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing the shortest path from
        starting_vertex to destination_vertex in
        breath-first order.
        """
        q = Queue()
        visited = set()
        q.enqueue([starting_vertex])

        while q.size() > 0:
            path = q.dequeue()
            current = path[-1]

            if current == destination_vertex:
                return path

            if current not in visited:
                visited.add(current)

                for i in self.get_neighbors(current):
                    q.enqueue(path + [i])
예제 #22
0
def get_shortest_path(start, end):
    # return list of shortest path id's from start to end using BFS
    qq = Queue()
    qq.enqueue([start])
    visited = set()

    while qq.size() > 0:
        path = qq.dequeue()
        if path[-1] not in visited:
            # mark room as visited
            visited.add(path[-1])
            if path[-1] == end:
                return path
            else:
                # find exits and find neig
                exits = world.rooms[path[-1]].get_exits()
                for direction in exits:
                    # add the neighbor to the queue
                    neighbor = world.rooms[path[-1]].get_room_in_direction(
                        direction)
                    print("unpack path? ", *path, "neigbor.id", neighbor.id)
                    qq.enqueue([*path, neighbor.id])
예제 #23
0
 def bfs(self, starting_vertex, destination_vertex):
     """
     Return a list containing the shortest path from
     starting_vertex to destination_vertex in
     breath-first order.
     """
     qq = Queue()
     visited = set()
     qq.enqueue([starting_vertex])
     while qq.size() > 0:
         path = qq.dequeue()
         vertex = path[-1]
         if vertex not in visited:
             # Did we find the target vertex
             if vertex == destination_vertex:
                 return path
             visited.add(vertex)
             for next_vert in self.vertices[vertex]:
                 # create a new list and not just a reference or shallow copy
                 new_path = list(path)
                 new_path.append(next_vert)
                 qq.enqueue(new_path)
예제 #24
0
    def bfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing the shortest path from
        starting_vertex to destination_vertex in
        breath-first order.
        """
        # Create an empty queue and enqueue A PATH TO the starting vertex ID
        q = Queue()
        # q.enqueue(starting_vertex)

        # Create a Set to store visited vertices
        visited = set()
        q.enqueue([starting_vertex])

        # While the queue is not empty...
        while q.size() > 0:
            # Dequeue the first PATH
            v = q.dequeue()

            # Grab the last vertex from the PATH
            n = v[-1]

            # If that vertex has not been visited...
            if n not in visited:
                # CHECK IF IT'S THE TARGET
                if n == destination_vertex:
                    # IF SO, RETURN PATH
                    return v

                # Mark it as visited...
                visited.add(n)

                # Then add A PATH TO its neighbors to the back of the queue
                for neighbor in self.vertices[n]:
                    # COPY THE PATH
                    new = v.copy()
                    # APPEND THE NEIGHOR TO THE BACK
                    new.append(neighbor)
                    q.enqueue(new)
예제 #25
0
 def bft(self, starting_vertex):
     """
     Print each vertex in breadth-first order
     beginning from starting_vertex.
     """
     # create an empty queue and enqueue the starting vertex ID
     q = Queue()
     q.enqueue(starting_vertex)
     # create a set to store the visited vertices
     visited = set()
     # while the queue is not empty
     while q.size() > 0:
         # Dequeue the first vertex
         v = q.dequeue()
         # if that vertex has not been vidited
         if v not in visited:
             # mark it as visited (printing for a representation)
             print(v)
             visited.add(v)
             # then add all of it's neighbors to the back of the queue
             for next_vertex in self.vertices[v]:
                 q.enqueue(next_vertex)
예제 #26
0
def myBFS(problem, current_position, visited_coords, parent_nodes,
          direction_nodes):
    nodes_Queue = Queue()

    while problem.isGoalState(current_position[0]) is not True:
        if (current_position[0]) in visited_coords:
            if nodes_Queue.isEmpty():
                break
            current_position = (nodes_Queue.pop())
            continue
        else:
            # print(current_position)
            nodes_to_expand = problem.getSuccessors(current_position[0])
            visited_coords[current_position[0]] = 'visited'

        for node in nodes_to_expand:
            # print(node[0])
            if visited_coords.get(node[0]) is None:
                nodes_Queue.push(node)
                # visited_coords[(node[0], node[2])] = 'visited'
                parent_nodes[node] = current_position
                direction_nodes[node] = node[1]
            if problem.isGoalState(node[0]):
                # print('visited:', visited_coords)
                # current_position = node
                visited_coords[node[0]] = 'visited'
                #
                parent_nodes[node] = current_position
                direction_nodes[node] = node[1]
                continue

        # if problem.isGoalState(current_position[0]):
        #     break
        else:
            if nodes_Queue.isEmpty():
                break
            current_position = (nodes_Queue.pop())

    return current_position
예제 #27
0
파일: graph.py 프로젝트: Memitaru/Graphs
    def bfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing the shortest path from
        starting_vertex to destination_vertex in
        breath-first order.
        """
        # make a queue and a visited set
        q = Queue()
        visited = set()

        path = [starting_vertex]

        # enqueue a path to the starting node

        q.enqueue(path)

        # while our queue isn't empty

        while q.size() > 0:
            # dequeue, this is our current_path
            current_path = q.dequeue()
            # whatever is list in the current_path is the current_node
            current_node = current_path[-1]
            # check if current-node is a destination_vertex
            if current_node == destination_vertex:
                return current_path
            # check if we've visited this node
            if current_node not in visited:
                visited.add(current_node)
                #get our neighbors
                neighbors = self.get_neighbors(current_node)
                # for each neighbor
                for neighbor in neighbors:
                    # make each neighbor its own copy of the path
                    path_copy = current_path[:]
                    # and add the nighbor to it
                    path_copy.append(neighbor)
                    # enqueue the path_copy
                    q.enqueue(path_copy)
예제 #28
0
    def bfs(self, starting_vertex, destination_vertex):
        """
        Return a list containing the shortest path from
        starting_vertex to destination_vertex in
        breadth-first order.
        """
        # make a queue
        q = Queue()
        # make a set to track nodes we've visited
        visited = set()

        path = [starting_vertex]
        q.enqueue(path)

        # while queue isn't empty
        while q.size() > 0:
            ## dequeue the path at the front of the line
            current_path = q.dequeue()
            current_node = current_path[-1]

            ### if this node is our target node
            if current_node == destination_vertex:
                #### return it!! return TRUE
                return current_path

        ### if not visited
            if current_node not in visited:
                #### mark as visited
                visited.add(current_node)
                #### get its neighbors
                neighbors = self.get_neighbors(current_node)
                #### for each neighbor
                for neighbor in neighbors:
                    ## copy path so we don't mutate the original path for different nodes
                    path_copy = current_path[:]
                    path_copy.append(neighbor)

                    ##### add to our queue
                    q.enqueue(path_copy)
예제 #29
0
파일: graph.py 프로젝트: dislersd/Graphs
    def bft(self, starting_vertex):
        """
        Print each vertex in breadth-first order
        beginning from starting_vertex.
        """

        # create an empty ser to store visited nodes
        visited = set()
        # create an empty que
        q = Queue()
        q.enqueue(starting_vertex)
        # while the queue is not empty...
        while q.size() > 0:
            # Deque the first vertex
            v = q.dequeue()
            # If that vertex has not been visited...
            if v not in visited:
                # Mark it as visited
                visited.add(v)
                # Then add all of its neighbors to the back of the queue
                for neighbor in self.vertices[v]:
                    q.enqueue(neighbor)
예제 #30
0
 def bft(self, starting_vertex):
     """
     Print each vertex in breadth-first order
     beginning from starting_vertex.
     """
     temp = []
     #make queue
     queue = Queue()
     #visited set
     visited = set()
     #put starting in queue
     queue.enqueue(starting_vertex)
     #while not empty, dequeue item, and mark item as visited
     while queue.size():
         node = queue.dequeue()
         visited.add(node)
         temp.append(node)
         #for each dequeued item edges, place in queue if not visited
         for edge in self.vertices[node]:
             if edge not in visited:
                 queue.enqueue(edge)
     print(temp)