1
+ '''
2
+ TOPOLOGICAL SORT :
3
+ Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge u v,
4
+ vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG.
5
+
6
+ For more Information about Topological Sort visit : https://cp-algorithms.com/graph/topological-sort.html
7
+
8
+ You are given a directed graph with n vertices and m edges.
9
+ You have to number the vertices so that every edge leads from the vertex with a smaller number assigned to the vertex with a larger one.
10
+ '''
11
+
1
12
from __future__ import print_function
13
+
2
14
'''
3
15
a
4
16
/ \
5
17
b c
6
18
/ \
7
19
d e
8
- '''
20
+ '''
21
+
9
22
edges = {'a' : ['c' , 'b' ], 'b' : ['d' , 'e' ], 'c' : [], 'd' : [], 'e' : []}
10
23
vertices = ['a' , 'b' , 'c' , 'd' , 'e' ]
11
24
12
25
13
26
def topological_sort (start , visited , sort ):
14
- """ Perform topolical sort on a directed acyclic graph."""
27
+ # Perform topolical sort on a directed acyclic graph.
15
28
current = start
16
29
# add current to visited
17
30
visited .append (current )
@@ -32,4 +45,12 @@ def topological_sort(start, visited, sort):
32
45
33
46
34
47
sort = topological_sort ('a' , [], [])
35
- print (sort )
48
+ print (sort ) # prints the sorted array
49
+
50
+ '''
51
+ OUTPUT : ['c', 'd', 'e', 'b', 'a']
52
+
53
+ Time Complexity: O(V+E).
54
+ The above algorithm is simply DFS so time complexity is the same as DFS which is. O(V+E).
55
+
56
+ '''
0 commit comments