Skip to content

Commit 0216344

Browse files
authored
Merge pull request #239 from Mohitkumar6122/patch-2
Create topological_sort.py
2 parents 442db0c + 473cbb2 commit 0216344

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
12+
from __future__ import print_function
13+
14+
'''
15+
a
16+
/ \
17+
b c
18+
/ \
19+
d e
20+
'''
21+
22+
edges = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []}
23+
vertices = ['a', 'b', 'c', 'd', 'e']
24+
25+
26+
def topological_sort(start, visited, sort):
27+
#Perform topolical sort on a directed acyclic graph.
28+
current = start
29+
# add current to visited
30+
visited.append(current)
31+
neighbors = edges[current]
32+
for neighbor in neighbors:
33+
# if neighbor not in visited, visit
34+
if neighbor not in visited:
35+
sort = topological_sort(neighbor, visited, sort)
36+
# if all neighbors visited add current to sort
37+
sort.append(current)
38+
# if all vertices haven't been visited select a new one to visit
39+
if len(visited) != len(vertices):
40+
for vertice in vertices:
41+
if vertice not in visited:
42+
sort = topological_sort(vertice, visited, sort)
43+
# return sort
44+
return sort
45+
46+
47+
sort = topological_sort('a', [], [])
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)