Write a program that finds strongly connected components in a directed graph.
- User
Write a program that finds strongly connected components in a directed graph.
Assistant
Write a program that finds strongly connected components in a directed graph.
The user wants a program to find Strongly Connected Components (SCCs) in a directed graph.
Choose the Algorithm:
Define the Steps for Kosaraju's Algorithm:
Select the Language:
Drafting the Code (Python):
def dfs1(v, visited, stack):
visited[v] = True
for u in graph[v]:
if not visited[u]:
dfs1(u, visited, stack)
stack.append(v)
transposed = [[] for _ in range(V)]
for v in range(V):
for u in graph[v]:
transposed[u].append(v)
def dfs2(v, visited, component):
visited[v] = True
component.append(v)
for u in transposed[v]:
if not visited[u]:
dfs2(u, visited, component)
V times for first pass. Iterate stack for second pass.Refining the Code Structure:
Graph is nice.Adding Explanations:
Self-Correction/Optimization:
Finalizing the Code Example:
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
# ... Step 1 DFS ...
# ... Step 2 Transpose ...
# ... Step 3 DFS ...
# ... Main SCC function ...
Alternative: Tarjan's Algorithm?
Constructing the Final Output:
This looks solid. I will write the Python code based on this plan.
(Self-Correction during coding): Make sure to handle 0-indexed vs 1-indexed nodes. I'll assume 0-indexed for simplicity, or generic hashing using defaultdict. defaultdict is safer.
Let's write out the code mentally:
fill_order: standard DFS pushing to stack.get_transpose: returns new graph with reversed edges.dfs_util: standard DFS that prints nodes.print_scs: orchestrates the above.Wait, the prompt asks for a program. I will provide Python. It's the most readable.
Code Structure:
class Graph:
def __init__(self, vertex_count):
self.vertex_count = vertex_count
self.adj = [[] for _ in range(vertex_count)]
def add_edge(self, u, v):
self.adj[u].append(v)
# Algo implementation...
Let's check logic on transposition. Original: 0 -> 1 Transpose: 1 -> 0 Correct.
Final check on Kosaraju logic:
Looks correct. I will produce the response now. Here is a complete implementation of Kosaraju’s Algorithm in Python. This algorithm is efficient with a time complexity of , where is the number of vertices and is the number of edges.
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
# --- Step 1: Fill vertices in stack according to their finishing times ---
def _fill_order(self, v, visited, stack):
visited[v] = True
for i in self.graph[v]:
if not visited[i]:
self._fill_order(i, visited, stack)
stack.append(v)
# --- Step 2: Create a reversed version of the graph ---
def _get_transpose(self):
g = Graph(self.V)
for i in self.graph:
for j in self.graph[i]:
g.add_edge(j, i)
return g
# --- Step 3: DFS utility to find all reachable vertices ---
def _dfs_util(self, v, visited, component):
visited[v] = True
component.append(v)
for i in self.graph[v]:
if not visited[i]:
self._dfs_util(i, visited, component)
# --- Main Function to Find and Print SCCs ---
def find_sccs(self):
stack = []
visited = [False] * (self.V)
# 1. Fill vertices in stack based on finishing times in original graph
for i in range(self.V):
if not visited[i]:
self._fill_order(i, visited, stack)
# 2. Create a transposed graph
gr = self._get_transpose()
# 3. Reset visited for the second pass
visited = [False] * (self.V)
sccs = []
# 4. Process vertices in order defined by Stack (decreasing finishing time)
while stack:
i = stack.pop()
if not visited[i]:
current_component = []
# All nodes reachable from 'i' in transposed graph form an SCC
gr._dfs_util(i, visited, current_component)
sccs.append(current_component)
return sccs
# --- Example Usage ---
if __name__ == "__main__":
# Create a graph given in the above diagram
# 0 -> 1 -> 2 -> 3 -> 4 -> 2 (Cycle involving 2,3,4)
# 0 -> 1
# 1 -> 0 (Cycle involving 0,1)
g = Graph(5)
g.add_edge(1, 0)
g.add_edge(0, 2)
g.add_edge(2, 1)
g.add_edge(0, 3)
g.add_edge(3, 4)
print("Strongly Connected Components are:")
sccs = g.find_sccs()
for component in sccs:
print(component)
If you run the code above, the output will identify the clusters of nodes that are reachable from each other. For the example provided:
[0, 1, 2] (The cycle ).[3] and [4] (as these are individual nodes not part of a cycle in this specific setup).