dvjsharma

Untitled

Aug 21st, 2025
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class Solution {
  5. public:
  6.     void allTopoSorts(vector<vector<int>>& adj, vector<int>& indegree,
  7.                       vector<bool>& visited, vector<int>& curr, int V) {
  8.         bool flag = false;
  9.  
  10.         for (int i = 0; i < V; i++) {
  11.             if (!visited[i] && indegree[i] == 0) {
  12.                 // choose this node
  13.                 visited[i] = true;
  14.                 curr.push_back(i);
  15.  
  16.                 // reduce indegree of neighbors
  17.                 for (int nbr : adj[i]) indegree[nbr]--;
  18.  
  19.                 // recurse
  20.                 allTopoSorts(adj, indegree, visited, curr, V);
  21.  
  22.                 // backtrack
  23.                 visited[i] = false;
  24.                 curr.pop_back();
  25.                 for (int nbr : adj[i]) indegree[nbr]++;
  26.                
  27.                 flag = true;
  28.             }
  29.         }
  30.  
  31.         // if no node was picked -> we found one valid order
  32.         if (!flag) {
  33.             for (int x : curr) cout << x << " ";
  34.             cout << "\n";
  35.         }
  36.     }
  37.  
  38.     void findAllTopologicalSorts(int V, vector<vector<int>>& edges) {
  39.         vector<vector<int>> adj(V);
  40.         vector<int> indegree(V, 0);
  41.  
  42.         for (auto& e : edges) {
  43.             adj[e[0]].push_back(e[1]);
  44.             indegree[e[1]]++;
  45.         }
  46.  
  47.         vector<bool> visited(V, false);
  48.         vector<int> curr;
  49.         allTopoSorts(adj, indegree, visited, curr, V);
  50.     }
  51. };
  52.  
  53. int main() {
  54.     int V = 4;
  55.     vector<vector<int>> edges = {
  56.         {0, 1}, {0, 2}, {1, 3}, {2, 3}
  57.     };
  58.  
  59.     Solution s;
  60.     cout << "All possible Topological Sorts:\n";
  61.     s.findAllTopologicalSorts(V, edges);
  62.  
  63.     return 0;
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment