We are asked: "Write a program to find all strongly connected components in a directed graph." So likely we need to produce code that computes SCCs using Kosaraju's algorithm or Tarjan's algorithm. Usually such tasks expect a concise solution.
We need to output the program. Possibly in a specific language? The prompt doesn't specify a language. Often these types of questions expect Python, but could also be C++ or Java. Since it's open-ended, I'll provide a Python implementation.
We should include explanation? The instruction is "Write a program to find all strongly connected components in a directed graph." So just provide the program.
We'll write a function that takes adjacency list representation of directed graph and returns list of SCCs.
Implementation using Kosaraju's algorithm:
Perform DFS on original graph, fill order stack with finishing times.
Transpose graph.
Process nodes in reverse order of finishing times, each DFS on transpose yields an SCC.
Or Tarjan's algorithm which is one-pass.
I'll go with Kosaraju for simplicity.
We need to handle vertices numbered from 0 to n-1 or possibly arbitrary labels. We'll assume vertices are 0..n-1.
Let's write:
def strongly_connected_components(n, edges):
# n: number of vertices
# edges: list of directed edges (u, v)
# returns list of lists, each list is SCC
adj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
# first pass
visited = [False]*n
order = []
def dfs1(v):
visited[v] = True
for u in adj[v]:
if not visited[u]:
dfs1(u)
order.append(v)
for v in range(n):
if not visited[v]:
dfs1(v)
# transpose
adj_t = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]:
adj_t[v].append(u)
# second pass
visited = [False]*n
sccs = []
def dfs2(v, comp):
visited[v] = True
comp.append(v)
for u in adj_t[v]:
if not visited[u]:
dfs2(u, comp)
while order:
v = order.pop()
if not visited[v]:
comp = []
dfs2(v, comp)
sccs.append(comp)
return sccs
That's the basic.
But perhaps we want to include a main to demonstrate. We can provide a complete script that reads input? The problem doesn't specify input format. Usually they want a function.
I'll provide a full program with a sample usage.
Alternatively, Tarjan's algorithm:
index = 0
stack = []
indices = [-1]*n
lowlink = [0]*n
onstack = [False]*n
sccs = []
def strongconnect(v):
global index
indices[v] = index
lowlink[v] = index
index += 1
stack.append(v)
onstack[v] = True
for w in adj[v]:
if indices[w] == -1:
strongconnect(w)
lowlink[v] = min(lowlink[v], lowlink[w])
elif onstack[w]:
lowlink[v] = min(lowlink[v], indices[w])
if lowlink[v] == indices[v]:
# root
scc = []
while True:
w = stack.pop()
onstack[w] = False
scc.append(w)
if w == v:
break
sccs.append(scc)
for v in range(n):
if indices[v] == -1:
strongconnect(v)
That's also fine.
Given that the instruction is simple, we can output either. I'll go with Kosaraju because it's straightforward and easier to explain.
But since the user just said "Write a program", I'll produce a clean program.
I'll write it in Python.
Let's produce:
python
def find_scc_kosaraju(n, edges):
# Build adjacency list
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u].append(v)
visited = [False] * n
order = []
def dfs1(v):
visited[v] = True
for w in graph[v]:
if not visited[w]:
dfs1(w)
order.append(v)
for v in range(n):
if not visited[v]:
dfs1(v)
# Build reverse graph
rev_graph = [[] for _ in range(n)]
for u in range(n):
for w in graph[u]:
rev_graph[w].append(u)
visited = [False] * n
sccs = []
def dfs2(v, component):
visited[v] = True
component.append(v)
for w in rev_graph[v]:
if not visited[w]:
dfs2(w, component)
while order:
v = order.pop()
if not visited[v]:
comp = []
dfs2(v, comp)
sccs.append(comp)
return sccs
Then maybe a main:
python
if __name__ == "__main__":
# Example usage
n = 8
edges = [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 5), (5, 3), (6, 7)]
sccs = find_scc_kosaraju(n, edges)
print("Strongly Connected Components:")
for i, comp in enumerate(sccs, 1):
print(f"Component {i}: {comp}")
That should output something like: Component 1: [0, 2, 1] etc.
We can also add docstring.
Thus answer.
But the instruction says "Write a program to find all strongly connected components in a directed graph." Possibly they expect a code snippet. I'll provide the full code.
We need to ensure it's correct and efficient.
Edge cases: graph with 0 vertices, etc. But we can ignore.
Now output as final answer.
I'll produce the code in a single block.
python
from typing import List, Tuple
def find_scc_kosaraju(n: int, edges: List[Tuple[int, int]]) -> List[List[int]]:
"""
Returns all strongly connected components (SCCs) of a directed graph
using Kosaraju's algorithm.
Parameters:
n: number of vertices (vertices are assumed to be 0 .. n-1)
edges: list of directed edges as tuples (u, v)
Returns:
A list of lists, each inner list contains the vertices of one SCC.
"""
# Build adjacency list
graph = [[] for _ in range(n)]
for u, v in edges:
graph[u].append(v)
# First DFS: record finishing order
visited = [False] * n
order = []
def dfs1(v: int) -> None:
visited[v] = True
for w in graph[v]:
if not visited[w]:
dfs1(w)
order.append(v)
for v in range(n):
if not visited[v]:
dfs1(v)
# Build reverse graph
rev_graph = [[] for _ in range(n)]
for u in range(n):
for w in graph[u]:
rev_graph[w].append(u)
# Second DFS on reverse graph in reverse finishing order
visited = [False] * n
sccs = []
def dfs2(v: int, component: List[int]) -> None:
visited[v] = True
component.append(v)
for w in rev_graph[v]:
if not visited[w]:
dfs2(w, component)
while order:
v = order.pop()
if not visited[v]:
comp = []
dfs2(v, comp)
sccs.append(comp)
return sccs
if __name__ == "__main__":
# Example usage
n = 8
edges = [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 5), (5, 3), (6, 7)]
sccs = find_scc_kosaraju(n, edges)
print("Strongly Connected Components:")
for i, comp in enumerate(sccs, 1):
print(f"Component {i}: {comp}")