11"""
22Topological Sort implementation using:
331. DFS-based approach
4- 2. Kahn's Algorithm (BFS-based)
4+ 2. Kahn's Algorithm (BFS-based approach )
55
66Topological sorting is applicable only for Directed Acyclic Graphs (DAGs).
7+
8+ Reference:
9+ https://en.wikipedia.org/wiki/Topological_sorting
710"""
811
9- from collections import deque , defaultdict
12+ from collections import deque
1013from typing import List
1114
1215
1316def topological_sort_dfs (vertices : int , edges : List [List [int ]]) -> List [int ]:
1417 """
1518 Perform topological sort using DFS.
1619
17- :param vertices: Number of vertices in the graph
18- :param edges: List of directed edges [u, v] where u -> v
19- :return: A list representing topological order
20- :raises ValueError: If a cycle is detected
20+ >>> order = topological_sort_dfs(
21+ ... 6, [[5, 2], [5, 0], [4, 0], [4, 1], [2, 3], [3, 1]]
22+ ... )
23+ >>> len(order) == 6
24+ True
2125 """
22- graph = defaultdict ( list )
26+ graph : List [ List [ int ]] = [[] for _ in range ( vertices )]
2327 for u , v in edges :
2428 graph [u ].append (v )
2529
26- visited = [0 ] * vertices # 0 = unvisited, 1 = visiting, 2 = visited
27- stack = []
30+ visited = [0 ] * vertices
31+ result : List [ int ] = []
2832
29- def dfs (node : int ):
33+ def dfs (node : int ) -> None :
3034 if visited [node ] == 1 :
3135 raise ValueError ("Graph contains a cycle" )
3236 if visited [node ] == 2 :
@@ -36,33 +40,34 @@ def dfs(node: int):
3640 for neighbor in graph [node ]:
3741 dfs (neighbor )
3842 visited [node ] = 2
39- stack .append (node )
43+ result .append (node )
4044
41- for v in range (vertices ):
42- if visited [v ] == 0 :
43- dfs (v )
45+ for vertex in range (vertices ):
46+ if visited [vertex ] == 0 :
47+ dfs (vertex )
4448
45- return stack [::- 1 ]
49+ return result [::- 1 ]
4650
4751
4852def topological_sort_kahn (vertices : int , edges : List [List [int ]]) -> List [int ]:
4953 """
50- Perform topological sort using Kahn's Algorithm (BFS) .
54+ Perform topological sort using Kahn's Algorithm.
5155
52- :param vertices: Number of vertices in the graph
53- :param edges: List of directed edges [u, v] where u -> v
54- :return: A list representing topological order
55- :raises ValueError: If a cycle is detected
56+ >>> order = topological_sort_kahn(
57+ ... 6, [[5, 2], [5, 0], [4, 0], [4, 1], [2, 3], [3, 1]]
58+ ... )
59+ >>> len(order) == 6
60+ True
5661 """
57- graph = defaultdict ( list )
62+ graph : List [ List [ int ]] = [[] for _ in range ( vertices )]
5863 in_degree = [0 ] * vertices
5964
6065 for u , v in edges :
6166 graph [u ].append (v )
6267 in_degree [v ] += 1
6368
64- queue = deque ([ i for i in range (vertices ) if in_degree [i ] == 0 ] )
65- topo_order = []
69+ queue = deque (i for i in range (vertices ) if in_degree [i ] == 0 )
70+ topo_order : List [ int ] = []
6671
6772 while queue :
6873 node = queue .popleft ()
@@ -76,21 +81,3 @@ def topological_sort_kahn(vertices: int, edges: List[List[int]]) -> List[int]:
7681 raise ValueError ("Graph contains a cycle" )
7782
7883 return topo_order
79-
80-
81- if __name__ == "__main__" :
82- vertices = 6
83- edges = [
84- [5 , 2 ],
85- [5 , 0 ],
86- [4 , 0 ],
87- [4 , 1 ],
88- [2 , 3 ],
89- [3 , 1 ],
90- ]
91-
92- print ("DFS-based Topological Sort:" )
93- print (topological_sort_dfs (vertices , edges ))
94-
95- print ("\n Kahn's Algorithm Topological Sort:" )
96- print (topological_sort_kahn (vertices , edges ))
0 commit comments