Skip to content

Commit cf7a2f9

Browse files
committed
add graph topological sort
1 parent 241115c commit cf7a2f9

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

graph/topological_sort.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
""" Topological Sort
2+
3+
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of
4+
vertices such that for every directed edge uv, vertex u comes before v in
5+
the ordering. Topological Sorting for a graph is not possible if the graph is
6+
not a DAG.
7+
"""
8+
9+
def topological_sort(graph):
10+
""" topological sort python implementation """
11+
stack = []
12+
visited = set()
13+
14+
def topological_sort_util(vertex):
15+
""" modified depth-first search recursive algorithm """
16+
visited.add(vertex)
17+
for node in graph[vertex]:
18+
if node not in visited:
19+
topological_sort_util(node)
20+
stack.append(vertex)
21+
22+
23+
for vertex in list(graph):
24+
if vertex not in visited:
25+
topological_sort_util(vertex)
26+
27+
stack.reverse()
28+
return stack
29+
30+
31+
def main():
32+
""" operational function """
33+
graph = {
34+
0: [1, 2, 5],
35+
1: [4],
36+
2: [],
37+
3: [2, 4, 5, 6],
38+
4: [],
39+
5: [2],
40+
6: [0, 4]
41+
}
42+
print(topological_sort(graph))
43+
44+
45+
if __name__ == "__main__":
46+
main()

0 commit comments

Comments
 (0)