Passed
Push — master ( be817c...e0c5f6 )
by Xianshun
01:49
created

MST.spanning_tree()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 3
rs 10
1
from abc import ABCMeta, abstractmethod
2
3
from pyalgs.algorithms.commons.union_find import UnionFind
4
from pyalgs.data_structures.commons.bag import Bag
5
from pyalgs.data_structures.commons.priority_queue import MinPQ
6
7
8
class MST(object):
9
    __metaclass__ = ABCMeta
10
11
    @abstractmethod
12
    def spanning_tree(self):
13
        pass
14
15
16
class KruskalMST(MST):
17
    tree = None
18
19
    def __init__(self, G):
20
        minpq = MinPQ.create()
21
        self.tree = Bag()
22
        for e in G.edges():
23
            minpq.enqueue(e)
24
25
        uf = UnionFind.create(G.vertex_count())
26
27
        while not minpq.is_empty() and self.tree.size() < G.vertex_count() - 1:
28
            e = minpq.del_min()
29
            v = e.start()
30
            w = e.end()
31
            if not uf.connected(v, w):
32
                uf.union(v, w)
33
                self.tree.add(e)
34
35
    def spanning_tree(self):
36
        return self.tree.iterate()
37