| @@ 41-78 (lines=38) @@ | ||
| 38 | return self._id[v] |
|
| 39 | ||
| 40 | ||
| 41 | class StronglyConnectedComponents(object): |
|
| 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 | ||
| @@ 7-38 (lines=32) @@ | ||
| 4 | from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph, Digraph |
|
| 5 | ||
| 6 | ||
| 7 | class ConnectedComponents(object): |
|
| 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 | class StronglyConnectedComponents(object): |
|