-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphIntro17.cpp
More file actions
83 lines (68 loc) · 1.29 KB
/
GraphIntro17.cpp
File metadata and controls
83 lines (68 loc) · 1.29 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
// Kosaraju Algorithm Strongly Connected Components
#include<bits/stdc++.h>
using namespace std;
#define V 8
#define pb push_back
unordered_map<int, vector<int>> adj, rev;
void DFS1(int i, vector<bool>& visited, stack<int>& mystack)
{
visited[i] = true;
for (int j : adj[i])
if (visited[j] == false)
DFS1(j, visited, mystack);
mystack.push(i);
}
void reverse()
{
for (int i = 0; i < V; ++i)
{
for (int j : adj[i])
rev[j].pb(i);
}
}
void DFS2(int i, vector<bool>& visited)
{
cout << i << " ";
visited[i] = true;
for (int j : rev[i])
if (!visited[j])
DFS2(j, visited);
}
void findSCCs()
{
stack<int> mystack;
vector<bool> visited(V, false);
for (int i = 0; i < V; ++i)
if (!visited[i])
DFS1(i, visited, mystack);
reverse();
for (int i = 0; i < V; ++i)
visited[i] = false;
cout << "Strongly Connected Components are:\n";
while (!mystack.empty())
{
int curr = mystack.top();
mystack.pop();
if (visited[curr] == false)
{
DFS2(curr, visited);
cout << "\n";
}
}
}
int main()
{
adj[0].pb(1);
adj[1].pb(2);
adj[2].pb(0);
adj[2].pb(3);
adj[3].pb(4);
adj[4].pb(5);
adj[4].pb(7);
adj[5].pb(6);
adj[6].pb(4);
adj[6].pb(7);
findSCCs();
return 0;
}
//TIME COMPLEXITY: O(V+E)