forked from VivekDubey9/Competitive-Programming-Algos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransposegraph.cpp
56 lines (48 loc) · 1.35 KB
/
transposegraph.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
// CPP program to find transpose of a graph.
#include <bits/stdc++.h>
using namespace std;
// function to add an edge from vertex source to vertex dest
void addEdge(vector<int> adj[], int src, int dest)
{
adj[src].push_back(dest);
}
// function to print adjacency list of a graph
void displayGraph(vector<int> adj[], int v)
{
for (int i = 0; i < v; i++) {
cout << i << "--> ";
for (int j = 0; j < adj[i].size(); j++)
cout << adj[i][j] << " ";
cout << "\n";
}
}
void transposeGraph(vector<int> adj[],
vector<int> transpose[], int v)
{
// traverse the adjacency list of given graph and
// for each edge (u, v) add an edge (v, u) in the
// transpose graph's adjacency list
for (int i = 0; i < v; i++)
for (int j = 0; j < adj[i].size(); j++)
addEdge(transpose, adj[i][j], i);
}
int main()
{
int v = 5;
vector<int> adj[v];
addEdge(adj, 0, 1);
addEdge(adj, 0, 4);
addEdge(adj, 0, 3);
addEdge(adj, 2, 0);
addEdge(adj, 3, 2);
addEdge(adj, 4, 1);
addEdge(adj, 4, 3);
// Finding transpose of graph represented
// by adjacency list adj[]
vector<int> transpose[v];
transposeGraph(adj, transpose, v);
// displaying adjacency list of transpose
// graph i.e. b
displayGraph(transpose, v);
return 0;
}