Beispiel #1
0
def BFS(graph, s):
    '''
    Breadth-first search implementation:
    BFS is an algorithm for traversing or searching tree or graph data structures.
    It starts at the tree root and explores the neighbor nodes first, before moving to the next level neighbours.

    :param graph: the graph to be searched, nodes have to be integers
    :param s: the source node, where the search begins
    :return: ordered list of nodes of BFS traversal
    '''

    if graph.count_nodes() == 0:
        return []

    visited = []
    bfs_trav = []

    queue = Queue()
    queue.push(s)
    visited.append(s)

    while not queue.is_empty():
        current = queue.pop()
        bfs_trav.append(current)

        print(current)
        for n in graph[current]:

            if n not in visited:
                print('node: {}'.format(n))
                queue.push(n)
                visited.append(n)

    return bfs_trav
Beispiel #2
0
def sorted_merge(A: list, B: list):
    """
    Time: O(A + B) actually O(2A + 2B), copying then reading back, with O(min(A, B)) comparisons in the worst case
    Space: O(n)
    :param A:
    :param B:
    :return:
    """
    p1, p2 = 0, len(A) - len(B)

    stack_A = Queue(iterable=A[:p2])
    stack_B = Queue(iterable=B)

    for i in range(len(A)):
        if stack_A.is_empty():
            A[i] = stack_B.pop()
        elif stack_B.is_empty():
            A[i] = stack_A.pop()
        elif stack_A.peek() <= stack_B.peek():
            A[i] = stack_A.pop()
        else:
            A[i] = stack_B.pop()
    return A