-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKhans_topological_Sort_Using_BFS.cpp
More file actions
80 lines (63 loc) · 1.87 KB
/
Copy pathKhans_topological_Sort_Using_BFS.cpp
File metadata and controls
80 lines (63 loc) · 1.87 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
#include "iostream"
#include "vector"
#include "set"
#include "map"
using namespace std;
struct Edge {
int source,destination;
};
class Graph{
int V;
vector<vector<int>> adjList;
vector<int> indegree;
public:
Graph(vector<Edge> edges,int V){
this->V = V;
adjList.resize(V);
indegree.resize(V,0);
for(auto i : edges){
adjList[i.source].push_back(i.destination);
indegree[i.destination]++;
}
}
bool Khans_Topological_Sort_BFS(vector<int> & L);
void printGraph();
};
void Graph :: printGraph()
{
for (int i = 0; i < adjList.size(); i++)
{
cout << i << " -- ";
for (int v : adjList[i])
cout <<"->"<< v << " ";
cout << endl;
}
}
bool Graph ::Khans_Topological_Sort_BFS(vector<int> &L) {
vector<int> SetOfIndegreeWith0IncomingNodes;
for(auto i = 0; i < indegree.size() ; i++) if(!indegree[i]) SetOfIndegreeWith0IncomingNodes.push_back(i);
while(!SetOfIndegreeWith0IncomingNodes.empty()){
int n = SetOfIndegreeWith0IncomingNodes.back(); SetOfIndegreeWith0IncomingNodes.pop_back();
L.push_back(n);
for (auto i : adjList[n]) {
indegree[i]--;
if(!indegree[i]) SetOfIndegreeWith0IncomingNodes.push_back(i);
}
}
return true ;
}
int main()
{
vector<Edge> edges ={ {0, 6}, {1, 2}, {1, 4}, {1, 6}, {3, 0}, {3, 4},
{5, 1}, {7, 0}, {7, 1}
};
set <int > setsize;
for(auto i : edges){ setsize.insert(i.source);setsize.insert(i.destination);}
int V = setsize.size();
Graph graph(edges, V);
vector<int> L;
// Perform Topological Sort
if (graph.Khans_Topological_Sort_BFS(L)) for (int i: L) cout << i << " ";
else cout << "Graph has at least one cycle. Topological sorting is not possible";
return 0;
}