File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
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 ()
You can’t perform that action at this time.
0 commit comments