Skip to main content

Strongly Connected Components - Kosaraju's Algorithm

Definition​

Kosaraju's Algorithm is a method used to find strongly connected components (SCCs) within a directed graph. It efficiently identifies groups of vertices where each vertex is reachable from every other vertex within the same group. This algorithm relies on depth-first search (DFS) techniques to traverse the graph twice, first to determine the order of vertices for the second traversal, and then to identify the SCCs

Practice​

kosaraju(graph):
order = [] # to store the order of vertices
visited = set() # set to keep track of visited vertices

# Phase 1: Perform DFS to determine the order of vertices
for each vertex in graph:
if vertex not in visited:
DFS(graph, vertex, visited, order)

# Transpose the graph
transposed_graph = transpose(graph)

# Phase 2: Perform DFS on the transposed graph in the determined order
visited.clear()
SCCs = []
while order is not empty:
vertex = order.pop()
if vertex not in visited:
SCC = []
DFS(transposed_graph, vertex, visited, SCC)
SCCs.append(SCC)

return SCCs

DFS(graph, vertex, visited, result):
visited.add(vertex)
for neighbor in graph[vertex]:
if neighbor not in visited:
DFS(graph, neighbor, visited, result)
result.append(vertex)

transpose(graph):
transposed_graph = {}
for vertex in graph:
transposed_graph[vertex] = []
for vertex in graph:
for neighbor in graph[vertex]:
transposed_graph[neighbor].append(vertex)
return transposed_graph