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
Example #2
0
 def setUp(self):
     self.uf = UnionFind(12)
Example #3
0
 def setUp(self):
     self.uf = UnionFind(12)
Example #4
0
class TestUnionFind(unittest.TestCase):

    def setUp(self):
        self.uf = UnionFind(12)

    def test_union(self):
        self.uf.union(1, 3)
        self.uf.union(2, 8)
        self.uf.union(9, 1)
        self.uf.union(4, 5)
        self.uf.union(9, 5)
        self.uf.union(10, 11)

        assert self.uf.find(1) == self.uf.find(4)
        assert self.uf.find(10) != self.uf.find(8)
        assert self.uf.find(2) == self.uf.find(8)
        assert max(self.uf.ranks) == 3
Example #5
0
class TestUnionFind(unittest.TestCase):
    def setUp(self):
        self.uf = UnionFind(12)

    def test_union(self):
        self.uf.union(1, 3)
        self.uf.union(2, 8)
        self.uf.union(9, 1)
        self.uf.union(4, 5)
        self.uf.union(9, 5)
        self.uf.union(10, 11)

        assert self.uf.find(1) == self.uf.find(4)
        assert self.uf.find(10) != self.uf.find(8)
        assert self.uf.find(2) == self.uf.find(8)
        assert max(self.uf.ranks) == 3