Skip to content

Commit 473cbb2

Browse files
Update topological_sort.py
1 parent 75bb920 commit 473cbb2

File tree

1 file changed

+24
-3
lines changed

1 file changed

+24
-3
lines changed

Arrays-Sorting/src/Topological Sort/topological_sort.py

+24-3
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,30 @@
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+
112
from __future__ import print_function
13+
214
'''
315
a
416
/ \
517
b c
618
/ \
719
d e
8-
'''
20+
'''
21+
922
edges = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []}
1023
vertices = ['a', 'b', 'c', 'd', 'e']
1124

1225

1326
def topological_sort(start, visited, sort):
14-
"""Perform topolical sort on a directed acyclic graph."""
27+
#Perform topolical sort on a directed acyclic graph.
1528
current = start
1629
# add current to visited
1730
visited.append(current)
@@ -32,4 +45,12 @@ def topological_sort(start, visited, sort):
3245

3346

3447
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

Comments
 (0)