# Python implementation of the above approach
class Solution:
# Topo sort only exists in DAGs i.e.
# Direct Acyclic graph
def dfs(self, adj, vis, node, n, stck):
vis[node] = 1
for it in adj[node]:
if not vis[it]:
self.dfs(adj, vis, it, n, stck)
stck.append(node)
# During the traversal u must
# be visited before v
def topo_sort(self, adj, n):
vis = [0] * n
# using stack ADT
stck = []
for i in range(n):
if not vis[i]:
self.dfs(adj, vis, i, n, stck)
return stck
def addEdge(adj, u, v):
adj[u].append(v)
# Drivers code
n = 6
adj = [[] for _ in range(n)]
addEdge(adj, 5, 0)
addEdge(adj, 5, 2)
addEdge(adj, 2, 0)
addEdge(adj, 2, 3)
addEdge(adj, 3, 0)
addEdge(adj, 3, 1)
addEdge(adj, 1, 0)
addEdge(adj, 4, 0)
addEdge(adj, 4, 1)
s1 = Solution()
ans = s1.topo_sort(adj, n)
for i in range(n):
num = ans.pop()
print(num, end=" ")
# This code is contributed by Tapesh(tapeshdua420)