Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- class Solution {
- public:
- void allTopoSorts(vector<vector<int>>& adj, vector<int>& indegree,
- vector<bool>& visited, vector<int>& curr, int V) {
- bool flag = false;
- for (int i = 0; i < V; i++) {
- if (!visited[i] && indegree[i] == 0) {
- // choose this node
- visited[i] = true;
- curr.push_back(i);
- // reduce indegree of neighbors
- for (int nbr : adj[i]) indegree[nbr]--;
- // recurse
- allTopoSorts(adj, indegree, visited, curr, V);
- // backtrack
- visited[i] = false;
- curr.pop_back();
- for (int nbr : adj[i]) indegree[nbr]++;
- flag = true;
- }
- }
- // if no node was picked -> we found one valid order
- if (!flag) {
- for (int x : curr) cout << x << " ";
- cout << "\n";
- }
- }
- void findAllTopologicalSorts(int V, vector<vector<int>>& edges) {
- vector<vector<int>> adj(V);
- vector<int> indegree(V, 0);
- for (auto& e : edges) {
- adj[e[0]].push_back(e[1]);
- indegree[e[1]]++;
- }
- vector<bool> visited(V, false);
- vector<int> curr;
- allTopoSorts(adj, indegree, visited, curr, V);
- }
- };
- int main() {
- int V = 4;
- vector<vector<int>> edges = {
- {0, 1}, {0, 2}, {1, 3}, {2, 3}
- };
- Solution s;
- cout << "All possible Topological Sorts:\n";
- s.findAllTopologicalSorts(V, edges);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment