-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKosaraju_Algorithm.cpp
More file actions
104 lines (84 loc) · 1.92 KB
/
Copy pathKosaraju_Algorithm.cpp
File metadata and controls
104 lines (84 loc) · 1.92 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
101
102
103
104
#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 dfs_stack(int source, stack<int> &s, vector<int> &visited)
{
visited[source] = 1;
for (auto v : graph[source])
{
if (!visited[v])
dfs_stack(v, s, visited);
}
s.push(source);
}
Graph transpose()
{
Graph g(V);
for (int i = 0; i < V; i++)
for (auto v : g.graph[i])
g.addEdge(v, i);
return g;
}
void dfs(int source, vector<int> &visited)
{
visited[source] = 1;
cout << source << " ";
for (auto v : graph[source])
{
if (!visited[v])
dfs(v, visited);
}
}
void Kosarajus_Algorithm(int source)
{
stack<int> s;
vector<int> visited(V, 0);
// Using DFS to store vertices in a stack.
for (int i = 0; i < V; i++)
{
if (!visited[i])
dfs_stack(i, s, visited);
}
// Transposing or revesring edges of the graph.
Graph tg = transpose();
// Again initializing visited vector with 0 for further use.
for (int i = 0; i < V; i++)
visited[i] = 0;
while (!s.empty())
{
int current = s.top();
s.pop();
if (!visited[current])
{
cout << "\nStrongly connected component : ";
tg.dfs(current, visited);
}
}
}
};
int main()
{
int V = 5;
Graph g(V);
g.addEdge(1, 0);
g.addEdge(0, 2);
g.addEdge(2, 1);
g.addEdge(0, 3);
g.addEdge(3, 4);
int source = 0;
g.Kosarajus_Algorithm(source);
return 0;
}