Skip to content

Commit ec3a574

Browse files
committed
Finalize topological sort with DFS and Kahn's algorithm
1 parent 8bb8fe7 commit ec3a574

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

data_structures/sort/topological_sort.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ def topological_sort_dfs(vertices: int, edges: list[list[int]]) -> list[int]:
4949
... )
5050
>>> len(order) == 6
5151
True
52+
53+
>>> topological_sort_dfs(2, [[0, 1], [1, 0]])
54+
Traceback (most recent call last):
55+
...
56+
ValueError: Graph contains a cycle
5257
"""
5358
graph: list[list[int]] = [[] for _ in range(vertices)]
5459
for u, v in edges:
@@ -73,6 +78,11 @@ def topological_sort_kahn(vertices: int, edges: list[list[int]]) -> list[int]:
7378
... )
7479
>>> len(order) == 6
7580
True
81+
82+
>>> topological_sort_kahn(2, [[0, 1], [1, 0]])
83+
Traceback (most recent call last):
84+
...
85+
ValueError: Graph contains a cycle
7686
"""
7787
graph: list[list[int]] = [[] for _ in range(vertices)]
7888
in_degree = [0] * vertices

0 commit comments

Comments
 (0)