Passed
Push — master ( dfbdfc...38602d )
by Xianshun
01:26
created

StronglyConnectedComponents.__init__()   B

Complexity

Conditions 5

Size

Total Lines 17

Duplication

Lines 17
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
dl 17
loc 17
rs 8.5454
c 1
b 0
f 0
1
from abc import ABCMeta, abstractmethod
2
3
from pyalgs.algorithms.graphs.topological_sort import DepthFirstOrder
4
from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph, Digraph
5
6
7 View Code Duplication
class ConnectedComponents(object):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
8
    marked = None
9
    _id = None
10
    _count = 0
11
12
    def __init__(self, G):
13
        if isinstance(G, EdgeWeightedGraph):
14
            G = G.to_graph()
15
16
        vertex_count = G.vertex_count()
17
        self.marked = [False] * vertex_count
18
        self._id = [-1] * vertex_count
19
        for v in range(vertex_count):
20
            if not self.marked[v]:
21
                self.dfs(G, v)
22
                self._count += 1
23
24
    def dfs(self, G, v):
25
        self.marked[v] = True
26
        self._id[v] = self._count
27
        for w in G.adj(v):
28
            if not self.marked[w]:
29
                self.dfs(G, w)
30
31
    def connected(self, v, w):
32
        return self._id[v] == self._id[w]
33
34
    def count(self):
35
        return self._count
36
37
    def id(self, v):
38
        return self._id[v]
39
40
41 View Code Duplication
class StronglyConnectedComponents(object):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
42
    marked = None
43
    _id = None
44
    _count = 0
45
46
    def __init__(self, G):
47
        if isinstance(G, EdgeWeightedGraph):
48
            raise ValueError('Graph must be directed graph for strongly connected components')
49
        if not isinstance(G, Digraph):
50
            raise ValueError('Graph must be directed graph for strongly connected components')
51
52
        vertex_count = G.vertex_count()
53
        self.marked = [False] * vertex_count
54
        self._id = [-1] * vertex_count
55
56
        dfo = DepthFirstOrder(G.reverse())
57
        orders = dfo.postOrder()
58
59
        for v in orders:
60
            if not self.marked[v]:
61
                self.dfs(G, v)
62
                self._count += 1
63
64
    def dfs(self, G, v):
65
        self.marked[v] = True
66
        self._id[v] = self._count
67
        for w in G.adj(v):
68
            if not self.marked[w]:
69
                self.dfs(G, w)
70
71
    def connected(self, v, w):
72
        return self._id[v] == self._id[w]
73
74
    def count(self):
75
        return self._count
76
77
    def id(self, v):
78
        return self._id[v]
79