-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGFG Graph-8 StrongConnectedComp.cpp
131 lines (106 loc) · 2.46 KB
/
GFG Graph-8 StrongConnectedComp.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <stdio.h>
#include <stdlib.h>
#include <bits/stdc++.h>
#include <vector>
#include <queue>
using namespace std;
vector <vector <int> > g;
vector <vector <int> > tg;
vector <bool> vis;
stack <int> s;
void addedge(int a, int b)
{
g[a].push_back(b);
}
void printgraph(int n)
{
for (int i=1;i<=n;i++)
{
for (int j=0;j<g[i].size();j++)
cout << g[i][j] << " ";
cout << endl;
}
}
void printTGgraph(int n)
{
cout << "Transpose Graph: " << endl;
for (int i=1;i<=n;i++)
{
for (int j=0;j<tg[i].size();j++)
cout << tg[i][j] << " ";
cout << endl;
}
}
void transpose_graph(int n)
{
for (int i=1;i<=n;i++)
{
for (int j=0;j<g[i].size();j++)
{
tg[g[i][j]].push_back(i);
}
}
}
void addtostack(int k) //here, for all nodes to which edge exists from k,
{ //are called again recursively and in the end k is entered in the stack. i.e all the components connected to k are added first in stack and k is entered later.
vis[k]=true;
for (int i=0;i<g[k].size();i++)
{
if (vis[g[k][i]]!=true)
addtostack(g[k][i]);
}
s.push(k);
}
void markingviswithstack(int k) //we basically mark all the components strongly connected to k as visited
{
vis[k]=true;
for (int i=0;i<tg[k].size();i++)
{
if (!vis[tg[k][i]])
{
cout << tg[k][i] << " " ;
markingviswithstack(tg[k][i]);
}
}
}
void kosaraju(int n)
{
vis.assign(n+1,false);
for (int i=1;i<=n;i++)
{
if (!vis[i])
addtostack(i);
}
vis.assign(n+1,false);
int cur,res=0;
while (!s.empty()) //stack is not empty
{
cur = s.top();
s.pop();
if (!vis[cur])
{
res++;
cout << res << " Connected Component: " << cur << " ";
markingviswithstack(cur);
cout << endl;
}
}
cout << "Total Strongly connected components are: " << res << endl;
}
int main()
{
int n,m,t1,t2;
cin >> n >> m;
g.assign(n+1,vector <int> () );
tg.assign(n+1,vector <int> () );
for (int i=1;i<=n;i++)
{
cin >> t1 >> t2;
addedge(t1,t2);
}
printgraph(n);
transpose_graph(n);
printTGgraph(n);
kosaraju(n);
return 0;
}