예제 #1
0
def kruskal(graph: UndirectedGraph) -> UndirectedGraph:
    """
    Kruskal's algorithm is a minimum-spanning-tree algorithm which finds an edge of the least possible weight
    that connects any two trees in the forest. It is a greedy algorithm in graph theory as it finds a minimum
    spanning tree for a connected weighted undirected graph adding increasing cost arcs at each step.
    Time complexity: O(E log V)
    """
    spanning_tree = UndirectedGraph()

    union_find = UnionFind(max(graph.get_vertices()) + 1)

    heap = FibonacciHeap(graph.get_all_edges())

    while not heap.is_empty():

        edge = heap.pop()

        # Only add the edge if it will not create a cycle
        if union_find.find(edge.a) != union_find.find(edge.b):
            spanning_tree.add_edge(edge.a, edge.b, edge.weight)
            union_find.union(edge.a, edge.b)

    return spanning_tree
예제 #2
0
 def setUp(self):
     self.uf = UnionFind(12)