forked from kothariji/competitive-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path(GEEKSFORGEEKS)Kosarajus algorithm.cpp
82 lines (69 loc) · 1.54 KB
/
(GEEKSFORGEEKS)Kosarajus algorithm.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
link : https://practice.geeksforgeeks.org/problems/strongly-connected-components-kosarajus-algo/1#
link : https://ideone.com/9MPtJm
Given a Directed Graph with V vertices and E edges, Find the number of strongly connected components in the graph.
*/
void DFSRec(vector<int> adj[], int s, stack<int> &st, bool visited[])
{
visited[s] = true;
for(int u : adj[s])
{
if(visited[u] == false)
{
DFSRec(adj, u, st, visited);
}
}
st.push(s);
}
void DFS(vector<int> adj[], int V, stack<int> &st)
{
bool visited[V];
fill(visited, visited+V, false);
for(int i = 0; i < V; i++)
{
if(visited[i] == false)
{
DFSRec(adj, i, st, visited);
}
}
}
void DFSRec1(vector<int> revadj[], int s, bool visited[])
{
visited[s] = true;
for(int u : revadj[s])
{
if(visited[u] == false)
{
DFSRec1(revadj, u, visited);
}
}
}
int kosaraju(int V, vector<int> adj[])
{
stack<int> st;
DFS(adj, V, st);
//Reverse Edges
vector<int> revadj[V];
for(int v = 0; v < V; v++)
{
for(int u: adj[v])
{
revadj[u].push_back(v);
}
}
//printStack(st);
int count = 0;
bool visited[V];
fill(visited, visited+V, false);
while(!st.empty())
{
int v = st.top();
st.pop();
if(visited[v] == false)
{
DFSRec1(revadj, v, visited);
count++;
}
}
return count;
}