-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathKosarajuAlgorithm.cpp
More file actions
70 lines (68 loc) · 1.72 KB
/
Copy pathKosarajuAlgorithm.cpp
File metadata and controls
70 lines (68 loc) · 1.72 KB
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
/* GFG Tested
Given a Directed Graph with V vertices and E edges, Find the number of strongly connected components in the graph.
*/
class Solution{
public:
/* Function to find the number of strongly connected components
* using Kosaraju's algorithm
* V: number of vertices
* adj[]: array of vectors to represent graph
*/
void DFS(stack<int> &ans,vector<int> adj[],int i,int *visited)
{
visited[i]=1;
for(auto it=adj[i].begin();it!=adj[i].end();it++)
{
if(!visited[*it])
{
DFS(ans,adj,*it,visited);
}
}
ans.push(i);
}
void DFSutil(vector<int> adj[],int i,int *visited)
{
visited[i]=1;
for(auto it=adj[i].begin();it!=adj[i].end();it++)
{
if(!visited[*it])
{
DFSutil(adj,*it,visited);
}
}
}
int kosaraju(int V, vector<int> adj[]) {
stack<int> finish;
int *visited=(int *)calloc(V,sizeof(int));
for(int i=0;i<V;i++)
{
if(!visited[i])
{
DFS(finish,adj,i,visited);
}
}
vector<int> *adj_t=new vector<int>[V];
for(int i=0;i<V;i++)
{
visited[i]=0;
for(auto it=adj[i].begin();it!=adj[i].end();it++)
{
adj_t[*it].push_back(i);
}
}
int c=0;
while(!finish.empty())
{
int val=finish.top();
finish.pop();
if(!visited[val])
{
DFSutil(adj_t,val,visited);
c++;
}
}
free(visited);
delete[] adj_t;
return c;
}
};