Skip to content

Commit 2768224

Browse files
authored
Create main.cpp
1 parent c4cf486 commit 2768224

File tree

1 file changed

+71
-0
lines changed
  • 23 - Graph Data Structure Problems/19 - Strongly Connected Components | Kosaraju's Algorithm

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
class Solution
2+
{
3+
public:
4+
// Function to perform Depth First Search (DFS) and populate the stack with nodes in order of their finish time
5+
void DFS(int node, vector<int>& visited, vector<vector<int>>& adjacencyList, stack<int>& nodesOrder) {
6+
// Mark the current node as visited
7+
visited[node] = true;
8+
9+
// Explore all unvisited neighbors of the current node
10+
for (auto neighbour : adjacencyList[node]) {
11+
if (!visited[neighbour])
12+
DFS(neighbour, visited, adjacencyList, nodesOrder);
13+
}
14+
15+
// After visiting all neighbors, push the current node onto the stack
16+
nodesOrder.push(node);
17+
}
18+
19+
// Function to perform DFS on the transposed graph
20+
void reverseDFS(int node, vector<vector<int>>& adjacencyList, vector<int>& visited) {
21+
// Mark the current node as visited
22+
visited[node] = true;
23+
24+
// Explore all unvisited neighbors of the current node in the transposed graph
25+
for (auto neighbour : adjacencyList[node]) {
26+
if (!visited[neighbour])
27+
reverseDFS(neighbour, adjacencyList, visited);
28+
}
29+
}
30+
31+
// Function to find the number of strongly connected components (SCCs) using Kosaraju's Algorithm
32+
int kosaraju(int V, vector<vector<int>>& adj) {
33+
// Step 1: Initialize visited vector and stack to store nodes in order of their finish time
34+
vector<int> visited(V, false);
35+
stack<int> nodesOrder;
36+
vector<vector<int>> transpose(V); // Adjacency list for the transposed graph
37+
int totalSCCs = 0; // Counter for SCCs
38+
39+
// Step 2: Perform DFS on the original graph to populate the stack
40+
for (int i = 0; i < V; i++) {
41+
if (!visited[i])
42+
DFS(i, visited, adj, nodesOrder);
43+
}
44+
45+
// Step 3: Create the transposed graph
46+
for (int i = 0; i < V; i++) {
47+
for (auto neighbour : adj[i]) {
48+
// Reverse the direction of edges
49+
transpose[neighbour].push_back(i);
50+
}
51+
}
52+
53+
// Step 4: Reset visited array for use in the second DFS
54+
fill(visited.begin(), visited.end(), false);
55+
56+
// Step 5: Perform DFS on the transposed graph in the order of nodes in the stack
57+
while (!nodesOrder.empty()) {
58+
int node = nodesOrder.top();
59+
nodesOrder.pop();
60+
61+
// If the node is not visited, it means we've found a new SCC
62+
if (!visited[node]) {
63+
totalSCCs++; // Increment SCC count
64+
reverseDFS(node, transpose, visited); // Explore all nodes in this SCC
65+
}
66+
}
67+
68+
// Step 6: Return the total number of SCCs
69+
return totalSCCs;
70+
}
71+
};

0 commit comments

Comments
 (0)