-
Notifications
You must be signed in to change notification settings - Fork 243
/
KosarajusAlgorithm.cpp
67 lines (48 loc) · 1.16 KB
/
KosarajusAlgorithm.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// https://www.codingninjas.com/codestudio/problems/count-strongly-connected-components-kosaraju-s-algorithm_1171151?leftPanelTab=1
#include<unordered_map>
#include<list>
#include<stack>
void dfs(int node, unordered_map<int, list<int>> &adj, vector<bool> &visited, stack<int> &topo){
visited[node]= true;
for(auto i : adj[node]){
if(!visited[i]){
dfs(i, adj, visited, topo);
}
}
topo.push(node);
}
void revDfs(int node, unordered_map<int, list<int>> &adj, vector<bool> &visited){
visited[node]= true;
for(auto i : adj[node]){
if(!visited[i])
revDfs(i, adj, visited);
}
}
int stronglyConnectedComponents(int v, vector<vector<int>> &edges)
{
unordered_map<int, list<int>> adj;
unordered_map<int, list<int>> transpose;
for(auto i : edges){
adj[i[0]].push_back(i[1]);
transpose[i[1]].push_back(i[0]);
}
vector<bool> visited(v, false);
stack<int> topo;
for(int i=0; i<v; i++){
if(!visited[i]){
dfs(i, adj, visited, topo);
}
}
for(int i=0; i<v; i++)
visited[i]= false;
int count= 0;
while(!topo.empty()){
int top= topo.top();
topo.pop();
if(!visited[top]){
count++;
revDfs(top, transpose, visited);
}
}
return count;
}