Skip to content

Commit fe61429

Browse files
author
Tushar Roy
committed
topological sorting in python
1 parent 13a801c commit fe61429

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

‎python/graph/topologicalsort.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#topological sort
2+
# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/TopologicalSort.java
3+
4+
from graph import Graph
5+
6+
def top_sort(graph):
7+
stack = []
8+
visited = set()
9+
for vertex in graph.all_vertex.values():
10+
if vertex in visited:
11+
continue
12+
top_sort_util(vertex, stack, visited)
13+
return stack
14+
15+
def top_sort_util(vertex, stack, visited):
16+
visited.add(vertex)
17+
for adjacent in vertex.adjacent_vertices:
18+
if adjacent in visited:
19+
continue
20+
top_sort_util(adjacent, stack, visited)
21+
stack.append(vertex)
22+
23+
if __name__ == '__main__':
24+
graph = Graph(True)
25+
graph.add_edge(1,3)
26+
graph.add_edge(1,2)
27+
graph.add_edge(3,4)
28+
graph.add_edge(5,6)
29+
graph.add_edge(6,3)
30+
graph.add_edge(3,8)
31+
graph.add_edge(8,11)
32+
33+
stack = top_sort(graph)
34+
35+
print(stack[::-1])
36+
37+
38+

0 commit comments

Comments
 (0)