-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTarjans_Algorithm.cpp
More file actions
100 lines (89 loc) · 2.3 KB
/
Copy pathTarjans_Algorithm.cpp
File metadata and controls
100 lines (89 loc) · 2.3 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
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
#include <bits/stdc++.h>
using namespace std;
class Graph
{
int V;
vector<int> *graph;
public:
Graph(int V)
{
this->V = V;
graph = new vector<int>[V];
}
void addEdge(int u, int v)
{
graph[u].push_back(v);
}
void printStack(stack<int> &s, int source, vector<int> &inStack)
{
cout << "Strongly connected components are : ";
while (s.top() != source)
{
cout << s.top() << " ";
inStack[s.top()] == -1;
s.pop();
}
cout << s.top() << " " << endl;
inStack[s.top()] == -1;
s.pop();
}
void Tarjans_Algorithm(int source, vector<int> &discovery, vector<int> &low, stack<int> &s, vector<int> &inStack)
{
static int time = 0;
discovery[source] = low[source] = ++time;
s.push(source);
inStack[source] = 1;
for (auto v : graph[source])
{
if (discovery[v] == -1)
{
Tarjans_Algorithm(v, discovery, low, s, inStack);
// Important STEP
low[source] = min(low[source], low[v]);
}
else if (inStack[v] == 1)
{
// Important STEP
low[source] = min(low[source], discovery[v]);
}
}
// Lastly printing the stack to get one component.
if (discovery[source] == low[source])
printStack(s, source, inStack);
}
};
int main()
{
int V = 11;
Graph g(V);
g.addEdge(0,1);
g.addEdge(0,3);
g.addEdge(1,2);
g.addEdge(1,4);
g.addEdge(2,0);
g.addEdge(2,6);
g.addEdge(3,2);
g.addEdge(4,5);
g.addEdge(4,6);
g.addEdge(5,6);
g.addEdge(5,7);
g.addEdge(5,8);
g.addEdge(5,9);
g.addEdge(6,4);
g.addEdge(7,9);
g.addEdge(8,9);
g.addEdge(9,8);
vector<int> discovery(V, -1);
vector<int> low(V, -1);
// Stack to print the vertices of one component.
stack<int> s;
// Vector to store the vertices present in the stack.
vector<int> inStack(V, -1);
for (int i = 0; i < V; i++)
{
// To make sure that no vertex is left un-discoveryed even the graph is undirected.
if (discovery[i] == -1)
g.Tarjans_Algorithm(i, discovery, low, s, inStack);
}
return 0;
}