Kosaraju's Algorithm
Kosaraju's Algorithm
Kosaraju's Algorithm
What is an SCC?
Key Insights
1. A directed graph and its transpose graph (reversing all edges) have the same SCCs.
2. The finishing times of nodes in the first DFS help us explore SCCs in the transpose graph in
reverse order.
Steps
1. First DFS:
Perform DFS to compute the finishing times of nodes.
Push nodes onto a stack in the order of completion.
2. Transpose the Graph:
Reverse the direction of all edges.
3. Second DFS:
Pop nodes from the stack.
Perform DFS on the transpose graph, visiting nodes in the stack order.
Each DFS traversal corresponds to one SCC.
Algorithm Components
1. Stack:
Maintains nodes by their finishing times during the first DFS.
2. Transpose Graph:
Reverses all edges of the original graph.
Pseudocode
1. Initialize:
- Stack to store finishing times.
- Visited array to track visited nodes.
C++ Implementation
// Function to perform DFS and store nodes in the stack by finishing time
void dfs(int node, vector<vector<int>>& adj, vector<int>& visited, stack<int>&
st) {
visited[node] = 1;
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
dfs(neighbor, adj, visited, st);
}
}
st.push(node);
}
int main() {
int V = 5;
vector<vector<int>> edges = {{0, 1}, {1, 2}, {2, 0}, {1, 3}, {3, 4}};
vector<vector<int>> sccs = findSCCs(V, edges);
return 0;
}
Example
Input Graph:
Vertices: 5
Edges: {(0,1),(1,2),(2,0),(1,3),(3,4)}{ (0,1), (1,2), (2,0), (1,3), (3,4) }
Output:
Time Complexity
Space Complexity