Advertisement
Araf_12

topological_sorting(DFS)

Apr 1st, 2025
548
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. vector<vector<int>> adj; // adjacency list of graph
  8. vector<int> visited;
  9. vector<int> ans; // will store the topological order
  10.  
  11. void dfs(int v) {
  12.     visited[v] = true;
  13.     for (int u : adj[v]) {
  14.         if (!visited[u])
  15.             dfs(u);
  16.     }
  17.     ans.push_back(v); // add vertex to the result after visiting all neighbors
  18. }
  19.  
  20. vector<int> topological_sort(int n) {
  21.     visited.assign(n, false);
  22.     ans.clear();
  23.    
  24.     for (int i = 0; i < n; ++i) {
  25.         if (!visited[i])
  26.             dfs(i);
  27.     }
  28.    
  29.     reverse(ans.begin(), ans.end()); // reverse to get correct topological order
  30.     return ans;
  31. }
  32.  
  33. int main() {
  34.     int n, m; // n = number of vertices, m = number of edges
  35.     cout << "Enter number of vertices and edges: ";
  36.     cin >> n >> m;
  37.    
  38.     adj.resize(n);
  39.     cout << "Enter edges (u v):" << endl;
  40.     for (int i = 0; i < m; ++i) {
  41.         int u, v;
  42.         cin >> u >> v;
  43.         adj[u].push_back(v);
  44.     }
  45.    
  46.     vector<int> topo_order = topological_sort(n);
  47.    
  48.     cout << "Topological order: ";
  49.     for (int v : topo_order) {
  50.         cout << v << " ";
  51.     }
  52.     cout << endl;
  53.    
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement