Skip to content

Commit 2fe9f46

Browse files
committed
add code for topological sort
1 parent 5f3a46f commit 2fe9f46

File tree

3 files changed

+41
-2
lines changed

3 files changed

+41
-2
lines changed

Diff for: README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
# geeksforgeeks practice
1+
# Algorithms practice
22

3-
My solutions to problem of [geeksforgeeks](http://www.geeksforgeeks.org/) portal
3+
This repository contains solutions to popular interview questions.

Diff for: a.out

50.1 KB
Binary file not shown.

Diff for: topological-sorting.cpp

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// https://www.geeksforgeeks.org/topological-sorting/
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
5+
void topoSort(vector<vector<int> > &g, vector<int> &visited, int v, stack<int> &s){
6+
visited[v] = 1;
7+
for(int i=0;i<g[v].size();i++){
8+
if(!visited[g[v][i]])
9+
topoSort(g,visited,g[v][i],s);
10+
}
11+
s.push(v);
12+
}
13+
14+
int main(){
15+
vector<vector <int> > g;
16+
int V = 6;
17+
vector<int > visited;
18+
g.resize(V+1);
19+
visited.resize(V+1);
20+
for(int i=0;i<V;i++)
21+
visited[i] = 0;
22+
g[5].push_back(0);
23+
g[5].push_back(2);
24+
g[4].push_back(0);
25+
g[4].push_back(1);
26+
g[2].push_back(3);
27+
g[3].push_back(1);
28+
stack<int > s;
29+
for(int i=0;i<V;i++){
30+
if(!visited[i])
31+
topoSort(g,visited,i,s);
32+
}
33+
while(!s.empty()){
34+
cout << s.top() << " ";
35+
s.pop();
36+
}
37+
cout << endl;
38+
return 0;
39+
}

0 commit comments

Comments
 (0)