|
| 1 | +from collections import defaultdict |
| 2 | + |
| 3 | +class Graph: |
| 4 | + def __init__(self, vertices): |
| 5 | + self.V = vertices # Number of vertices |
| 6 | + self.graph = defaultdict(list) # Default dictionary to store the graph |
| 7 | + |
| 8 | + def add_edge(self, u, v): |
| 9 | + """Function to add an edge from vertex u to vertex v.""" |
| 10 | + self.graph[u].append(v) |
| 11 | + |
| 12 | + def _dfs(self, v, visited, stack=None): |
| 13 | + """ |
| 14 | + A recursive function to perform DFS from vertex v. |
| 15 | + If stack is provided, it pushes the vertices in the order of their finish time. |
| 16 | + """ |
| 17 | + visited[v] = True |
| 18 | + # Recur for all vertices adjacent to this vertex |
| 19 | + for neighbor in self.graph[v]: |
| 20 | + if not visited[neighbor]: |
| 21 | + self._dfs(neighbor, visited, stack) |
| 22 | + |
| 23 | + # Push the vertex to stack if it's not None (used in first DFS pass) |
| 24 | + if stack is not None: |
| 25 | + stack.append(v) |
| 26 | + |
| 27 | + def _transpose(self): |
| 28 | + """ |
| 29 | + Function to transpose (reverse) the graph. |
| 30 | + Returns the transposed graph. |
| 31 | + """ |
| 32 | + transposed = Graph(self.V) |
| 33 | + for vertex in self.graph: |
| 34 | + for neighbor in self.graph[vertex]: |
| 35 | + transposed.add_edge(neighbor, vertex) |
| 36 | + return transposed |
| 37 | + |
| 38 | + def kosaraju_scc(self): |
| 39 | + """ |
| 40 | + Function to find and print all Strongly Connected Components (SCCs) using Kosaraju's Algorithm. |
| 41 | + Returns a list of SCCs, where each SCC is a list of vertices. |
| 42 | + """ |
| 43 | + # Step 1: Perform DFS to get the finishing times of vertices |
| 44 | + stack = [] |
| 45 | + visited = [False] * self.V |
| 46 | + |
| 47 | + for i in range(self.V): |
| 48 | + if not visited[i]: |
| 49 | + self._dfs(i, visited, stack) |
| 50 | + |
| 51 | + # Step 2: Transpose the graph |
| 52 | + transposed_graph = self._transpose() |
| 53 | + |
| 54 | + # Step 3: Process vertices in the order defined by the stack |
| 55 | + visited = [False] * self.V |
| 56 | + sccs = [] # List to store SCCs |
| 57 | + |
| 58 | + while stack: |
| 59 | + v = stack.pop() |
| 60 | + if not visited[v]: |
| 61 | + # Collect all vertices in the current SCC |
| 62 | + scc_stack = [] |
| 63 | + transposed_graph._dfs(v, visited, scc_stack) |
| 64 | + sccs.append(scc_stack) |
| 65 | + |
| 66 | + return sccs |
| 67 | + |
| 68 | +# Example usage |
| 69 | +if __name__ == "__main__": |
| 70 | + g = Graph(5) |
| 71 | + g.add_edge(1, 0) |
| 72 | + g.add_edge(0, 2) |
| 73 | + g.add_edge(2, 1) |
| 74 | + g.add_edge(0, 3) |
| 75 | + g.add_edge(3, 4) |
| 76 | + |
| 77 | + print("Strongly Connected Components:") |
| 78 | + sccs = g.kosaraju_scc() |
| 79 | + for i, scc in enumerate(sccs, 1): |
| 80 | + print(f"SCC {i}: {scc}") |
0 commit comments