-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGraph_Topolocial_Sort_UsingBFS.cpp
More file actions
108 lines (83 loc) · 2.14 KB
/
Graph_Topolocial_Sort_UsingBFS.cpp
File metadata and controls
108 lines (83 loc) · 2.14 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
105
106
107
108
#include<iostream>
#include<map>
#include<list>
#include<queue>
using namespace std;
template<typename T>
class Graph{
map<T,list<T> > adjList;
public:
Graph()
{
}
void addEdge(T u,T v,bool bidir=true){
adjList[u].push_back(v);
if(bidir)
{
adjList[v].push_back(u);
}
}
void bfsTopologicalSort(){
queue<T> q;
map<T,bool> visited;
map<T,int> indegree;
for(auto i:adjList)
{
//i is pair(node,list of nodes)
T node = i.first;
visited[node]=false;
indegree[node]=0;
}
//In the indegrees of all nodes
for(auto i:adjList)
{
T u=i.first;
for(T v:adjList[u])
{
indegree[v]++;
}
}
//Find out all the nodes with 0 indegree
for(auto i:adjList)
{
T node=i.first;
if(indegree[node]==0)
{
q.push(node);
}
}
//Start with algorithm
while(!q.empty())
{
T node = q.front();
q.pop();
cout<<node<<"-->";
for(T neighbour:adjList[node])
{
indegree[neighbour]--;
if(indegree[neighbour]==0)
{
q.push(neighbour);
}
}
}
}
};
int main()
{
Graph<string> g;
g.addEdge("English","Programming Logic",false);
g.addEdge("Maths","Programming Logic",false);
g.addEdge("Programming Logic","HTML",false);
g.addEdge("Programming Logic","Python",false);
g.addEdge("Programming Logic","Java",false);
g.addEdge("Programming Logic","JS",false);
g.addEdge("Python","Web Dev",false);
g.addEdge("HTML","CSS",false);
g.addEdge("CSS","JS",false);
g.addEdge("JS","Web Dev",false);
g.addEdge("Java","Web Dev",false);
g.addEdge("Python","Web Dev",false);
g.bfsTopologicalSort();
return 0;
}