File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < bits/stdc++.h>
2+ using namespace std ;
3+
4+ void addEdge (vector<int > adj[], int u, int v)
5+ {
6+ adj[u].push_back (v);
7+ }
8+
9+ void topologicalSort (vector<int > adj[], int v)// time comp. O(V+E) ; space comp. O(V)
10+ {
11+ vector<int > inDegree (v, 0 );
12+
13+ for (int i = 0 ; i < v; i++)
14+ {
15+ for (auto x : adj[i])
16+ {
17+ inDegree[x]++;
18+ }
19+ }
20+
21+ queue<int > q;
22+
23+ for (int i = 0 ; i < v; i++)
24+ {
25+ if (inDegree[i] == 0 )
26+ {
27+ q.push (i);
28+ }
29+ }
30+
31+ while (!q.empty ())
32+ {
33+ int u = q.front ();
34+ q.pop ();
35+
36+ cout << u << " " ;
37+
38+ for (auto x : adj[u])
39+ {
40+ inDegree[x]--;
41+ if (inDegree[x] == 0 )
42+ {
43+ q.push (x);
44+ }
45+ }
46+ }
47+ }
48+
49+ int main ()
50+ {
51+ int v = 5 ;
52+ vector<int > adj[v];
53+
54+ addEdge (adj, 0 , 2 );
55+ addEdge (adj, 0 , 3 );
56+ addEdge (adj, 1 , 3 );
57+ addEdge (adj, 1 , 4 );
58+ addEdge (adj, 2 , 3 );
59+
60+ topologicalSort (adj, v);
61+ return 0 ;
62+ }
You can’t perform that action at this time.
0 commit comments