1+ #Python program to print topological sorting of a DAG
2+ from collections import defaultdict
3+
4+ #Class to represent a graph
5+ class Graph :
6+ def __init__ (self ,vertices ):
7+ self .graph = defaultdict (list ) #dictionary containing adjacency List
8+ self .V = vertices #No. of vertices
9+
10+ # function to add an edge to graph
11+ def addEdge (self ,u ,v ):
12+ self .graph [u ].append (v )
13+
14+ # A recursive function used by topologicalSort
15+ def topologicalSortUtil (self ,v ,visited ,stack ):
16+
17+ # Mark the current node as visited.
18+ visited [v ] = True
19+
20+ # Recur for all the vertices adjacent to this vertex
21+ for i in self .graph [v ]:
22+ if visited [i ] == False :
23+ self .topologicalSortUtil (i ,visited ,stack )
24+
25+ # Push current vertex to stack which stores result
26+ stack .insert (0 ,v )
27+
28+ # The function to do Topological Sort. It uses recursive
29+ # topologicalSortUtil()
30+ def topologicalSort (self ):
31+ # Mark all the vertices as not visited
32+ visited = [False ]* self .V
33+ stack = []
34+
35+ # Call the recursive helper function to store Topological
36+ # Sort starting from all vertices one by one
37+ for i in range (self .V ):
38+ if visited [i ] == False :
39+ self .topologicalSortUtil (i ,visited ,stack )
40+
41+ # Print contents of the stack
42+ print stack
43+
44+ g = Graph (6 )
45+ g .addEdge (5 , 2 );
46+ g .addEdge (5 , 0 );
47+ g .addEdge (4 , 0 );
48+ g .addEdge (4 , 1 );
49+ g .addEdge (2 , 3 );
50+ g .addEdge (3 , 1 );
51+
52+ print "Following is a Topological Sort of the given graph"
53+ g .topologicalSort ()
0 commit comments