<script>
class Graph{
constructor(edges, N){
this
.adjList =
new
Array(N);
for
(let i = 0; i < N; i++){
this
.adjList[i] =
new
Array();
}
this
.indegree =
new
Array(N).fill(0);
for
(let i = 0; i < edges.length; i++){
let src = edges[i][0];
let dest = edges[i][1];
this
.adjList[src].push(dest);
this
.indegree[dest] =
this
.indegree[dest] + 1;
}
}
}
function
findAllTopologicalOrders(graph, path, discovered, N){
for
(let v = 0; v < N; v++){
if
(graph.indegree[v] == 0 && !discovered[v]){
for
(let indx = 0; indx < graph.adjList[v].length; indx++){
let u = graph.adjList[v][indx];
graph.indegree[u] = graph.indegree[u] - 1;
}
}
path.push(v);
discovered[v] =
true
;
findAllTopologicalOrders(graph, path, discovered, N)
for
(let indx = 0; indx < graph.adjList[v].length; indx++){
let u = graph.adjList[v][indx];
graph.indegree[u] = graph.indegree[u] + 1;
}
path.pop();
discovered[v] =
false
;
}
if
(path.length == N){
console.log(path);
}
}
function
printAllTopologicalOrders(graph){
let N = graph.adjList.length;
let discovered =
new
Array(N).fill(
false
);
let path = [];
findAllTopologicalOrders(graph, path, discovered, N)
}
let edges = [[5, 2], [5, 0], [4, 0], [4, 1], [2, 3], [3, 1]];
console.log(
"All Topological sorts"
);
let N = 6;
let graph =
new
Graph(edges, N);
printAllTopologicalOrders(graph);
</script>