TheAlgorithms-C-Plus-Plus/graph/Topological-Sort.cpp

54 lines
988 B
C++
Raw Normal View History

2018-11-20 21:30:46 +08:00
#include <iostream>
#include <vector>
#include <algorithm>
2019-08-21 10:10:08 +08:00
using namespace std;
2018-11-20 21:30:46 +08:00
2019-08-21 10:10:08 +08:00
int n, m; // For number of Vertices (V) and number of edges (E)
vector<vector<int>> G;
2018-11-20 21:30:46 +08:00
vector<bool> visited;
vector<int> ans;
2019-08-21 10:10:08 +08:00
void dfs(int v)
{
2018-11-20 21:30:46 +08:00
visited[v] = true;
2019-08-21 10:10:08 +08:00
for (int u : G[v])
{
2018-11-20 21:30:46 +08:00
if (!visited[u])
dfs(u);
}
ans.push_back(v);
}
2019-08-21 10:10:08 +08:00
void topological_sort()
{
2018-11-20 21:30:46 +08:00
visited.assign(n, false);
ans.clear();
2019-08-21 10:10:08 +08:00
for (int i = 0; i < n; ++i)
{
2018-11-20 21:30:46 +08:00
if (!visited[i])
dfs(i);
}
reverse(ans.begin(), ans.end());
}
2019-08-21 10:10:08 +08:00
int main()
{
2019-02-20 02:45:38 +08:00
cout << "Enter the number of vertices and the number of directed edges\n";
2018-11-20 21:30:46 +08:00
cin >> n >> m;
2019-08-21 10:10:08 +08:00
int x, y;
G.resize(n, vector<int>());
for (int i = 0; i < n; ++i)
{
2018-11-20 21:30:46 +08:00
cin >> x >> y;
2019-08-21 10:10:08 +08:00
x--, y--; // to convert 1-indexed to 0-indexed
2018-11-20 21:30:46 +08:00
G[x].push_back(y);
}
topological_sort();
cout << "Topological Order : \n";
2019-08-21 10:10:08 +08:00
for (int v : ans)
{
2019-02-20 02:45:38 +08:00
cout << v + 1 << ' '; // converting zero based indexing back to one based.
2018-11-20 21:30:46 +08:00
}
cout << '\n';
return 0;
}