def test_queue(self):
     queue = BasicQueue()
     queue.enqueue("John")
     queue.enqueue("Alex")
     queue.enqueue("Irina")
     while queue.isEmpty() is not True:
         print(queue.dequeue())
Example #2
0
def cosarayuIterative(vertexIndexes: []):
    adjacencyVector = makeAdjacencyVector(vertexIndexes)
    vertexes = makeVertexesArray(vertexIndexes, adjacencyVector)

    invertedVector = adjacencyVector.getInvertedVector()
    invertedVertexes = deepcopy(vertexes)

    for rowVertexIndex, rowBindedVertexIndexes in enumerate(
            invertedVector.vector):
        invertedVertexes[rowVertexIndex].clearBindedIndexes()
        for bindedVertexIndex in rowBindedVertexIndexes:
            invertedVertexes[rowVertexIndex].addBindedVertex(
                invertedVertexes[bindedVertexIndex])

    components = Dictionary()
    compVertexesQueue = BasicQueue()
    compVertexesStack = BasicStack()

    invertedMatrix = adjacencyVector.getInvertedVector()

    for rowVertexIndex, rowBindedVertexIndexes in enumerate(
            invertedMatrix.vector):
        invertedVertexes[rowVertexIndex].clearBindedIndexes()
        for bindedVertexIndex in rowBindedVertexIndexes:
            invertedVertexes[rowVertexIndex].addBindedVertex(
                invertedVertexes[bindedVertexIndex])

    invertedVertexes[0].passed = True

    cache = VectorArray()

    for rowVertexIndex, rowBindedVertexIndexes in enumerate(
            invertedMatrix.vector):
        indexCachedVertex = cache.getIndexByValue(rowVertexIndex)
        if indexCachedVertex is not None:
            continue
        cache.add(invertedVertexes[rowVertexIndex].index)
        compVertexesQueue.enqueue(rowVertexIndex)

        for vertexIndex in rowBindedVertexIndexes:
            cachedVertex = cache.getIndexByValue(vertexIndex)
            if cachedVertex is not None:
                continue
            vertex = invertedVertexes[vertexIndex]
            if vertex.passed is False:
                DFSIterative(vertex, compVertexesQueue, cache,
                             invertedVertexes)
        while not compVertexesQueue.isEmpty():
            compVertexesStack.push(compVertexesQueue.dequeue())

    component_index = 0
    cache = SingleArray()

    while not compVertexesStack.isEmpty():
        vertexIndex = compVertexesStack.pop()
        if components[vertexIndex] is None:
            DFS2Iterative(vertexIndex, components, component_index, vertexes,
                          cache)
            component_index += 1

    return components.get_all()
Example #3
0
def cosarayu(vertexIndexes: []):
    # Создаём из входного массива вектор смежности
    adjacencyVector = makeAdjacencyVector(vertexIndexes)

    # Создаём из вектора смежности массив вершин, связываем вершины друг с другом
    vertexes = makeVertexesArray(vertexIndexes, adjacencyVector)

    # Создаём инвертированный вектор смежности
    invertedVector = adjacencyVector.getInvertedVector()

    # Копируем массив вершин и меняем связи между вершинами
    # в соответствии с инвертированным вектором смежности
    invertedVertexes = deepcopy(vertexes)

    for masterVertexIndex, slaveVertexIndexes in enumerate(
            invertedVector.vector):
        invertedVertexes[masterVertexIndex].clearBindedIndexes()
        for slaveVertexIndex in slaveVertexIndexes:
            invertedVertexes[masterVertexIndex].addBindedVertex(
                invertedVertexes[slaveVertexIndex])

    # Словарь для хранения вершин компонентов
    # Ключ - индекс вершины,
    # Значение - номер компонента
    components = Dictionary()

    # Очередь для хранения вершин одной компоненты связности
    compVertexesQueue = BasicQueue()

    # Стек для хранения вершин, упорядоченных по принадлежности к компонентам,
    # который мы будем проходить снизу вверх, заполняя массив components
    compVertexesStack = BasicStack()

    # Первая вершина считается пройденной
    invertedVertexes[0].passed = True

    # Проходим каждую вершину и связанные с ней вершины
    for masterVertexIndex, slaveVertexIndexes in enumerate(
            invertedVector.vector):
        for vertexIndex in slaveVertexIndexes:
            vertex = invertedVertexes[vertexIndex]

            # Если вершина ещё не пройдена,
            # то запускаем процедуру поиска в глубину
            if vertex.passed is False:
                DFS1(vertex, compVertexesQueue)

        if not compVertexesQueue.isEmpty() \
            and not compVertexesQueue.isValueExists(masterVertexIndex):
            compVertexesQueue.enqueue(masterVertexIndex)

        # Если временная очередь не пуста,
        # то надо добавить её содержимое в стек для хранения вершин
        while not compVertexesQueue.isEmpty():
            compVertexesStack.push(compVertexesQueue.dequeue())

    component_index = 0

    while not compVertexesStack.isEmpty():
        vertexIndex = compVertexesStack.pop()
        if components[vertexIndex] is None:
            DFS2(vertexIndex, components, component_index, vertexes)
            component_index += 1

    return components.get_all()