Tarjan's algorithm is a popular algorithm used to find the strongly connected components (SCCs) in a directed graph. A strongly connected component is a set of vertices where there is a path between every pair of vertices. This algorithm is based on depth-first search (DFS) and uses a stack to keep track of the visited nodes.
function TarjanSCC(graph):
index := 0
stack := empty stack
indexMap := map of nodes to their index values
lowLinkMap := map of nodes to their low-link values
onStack := set of nodes on the stack
SCCs := empty list
for each node in graph:
if node is unvisited:
DFS(node)
function DFS(node):
indexMap[node] := index
lowLinkMap[node] := index
index := index + 1
stack.push(node)
onStack.add(node)
for each neighbor in neighbors of node:
if neighbor is unvisited:
DFS(neighbor)
lowLinkMap[node] := minimum(lowLinkMap[node], lowLinkMap[neighbor])
else if neighbor is on stack:
lowLinkMap[node] := minimum(lowLinkMap[node], indexMap[neighbor])
if lowLinkMap[node] == indexMap[node]:
SCC := empty list
while true:
poppedNode := stack.pop()
onStack.remove(poppedNode)
SCC.add(poppedNode)
if poppedNode == node:
break
SCCs.add(SCC)
return SCCs
Tarjan's algorithm uses DFS to visit nodes in the graph and assigns each node an index and low-link value. The index represents the order in which the nodes are visited during the DFS traversal, and the low-link value is the minimum index of any node reachable from the current node.
The algorithm maintains a stack to keep track of the visited nodes. When a node is visited, it is pushed onto the stack and marked as on the stack. The algorithm performs a recursive DFS on each unvisited neighbor of the current node, updating the low-link value of the current node based on the low-link values of its neighbors.
If the low-link value of a node is equal to its index, it means that the current node and all nodes above it in the stack form a strongly connected component. These nodes are popped from the stack and added to a list representing the SCC.
The algorithm continues the DFS traversal until all nodes have been visited. At the end, the algorithm returns a list of SCCs present in the graph.
Tarjan's algorithm is efficient for finding SCCs in a graph and has a time complexity of