|
1 |
| -def topological_sort(graph): |
| 1 | +def topological_sort(graph: dict[int, list[int]]) -> list[int] | None: |
2 | 2 | """
|
3 |
| - Kahn's Algorithm is used to find Topological ordering of Directed Acyclic Graph |
4 |
| - using BFS |
| 3 | + Perform topological sorting of a Directed Acyclic Graph (DAG) |
| 4 | + using Kahn's Algorithm via Breadth-First Search (BFS). |
| 5 | +
|
| 6 | + Topological sorting is a linear ordering of vertices in a graph such that for |
| 7 | + every directed edge u → v, vertex u comes before vertex v in the ordering. |
| 8 | +
|
| 9 | + Parameters: |
| 10 | + graph: Adjacency list representing the directed graph where keys are |
| 11 | + vertices, and values are lists of adjacent vertices. |
| 12 | +
|
| 13 | + Returns: |
| 14 | + The topologically sorted order of vertices if the graph is a DAG. |
| 15 | + Returns None if the graph contains a cycle. |
| 16 | +
|
| 17 | + Example: |
| 18 | + >>> graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} |
| 19 | + >>> topological_sort(graph) |
| 20 | + [0, 1, 2, 3, 4, 5] |
| 21 | +
|
| 22 | + >>> graph_with_cycle = {0: [1], 1: [2], 2: [0]} |
| 23 | + >>> topological_sort(graph_with_cycle) |
5 | 24 | """
|
| 25 | + |
6 | 26 | indegree = [0] * len(graph)
|
7 | 27 | queue = []
|
8 |
| - topo = [] |
9 |
| - cnt = 0 |
| 28 | + topo_order = [] |
| 29 | + processed_vertices_count = 0 |
10 | 30 |
|
| 31 | + # Calculate the indegree of each vertex |
11 | 32 | for values in graph.values():
|
12 | 33 | for i in values:
|
13 | 34 | indegree[i] += 1
|
14 | 35 |
|
| 36 | + # Add all vertices with 0 indegree to the queue |
15 | 37 | for i in range(len(indegree)):
|
16 | 38 | if indegree[i] == 0:
|
17 | 39 | queue.append(i)
|
18 | 40 |
|
| 41 | + # Perform BFS |
19 | 42 | while queue:
|
20 | 43 | vertex = queue.pop(0)
|
21 |
| - cnt += 1 |
22 |
| - topo.append(vertex) |
23 |
| - for x in graph[vertex]: |
24 |
| - indegree[x] -= 1 |
25 |
| - if indegree[x] == 0: |
26 |
| - queue.append(x) |
27 |
| - |
28 |
| - if cnt != len(graph): |
29 |
| - print("Cycle exists") |
30 |
| - else: |
31 |
| - print(topo) |
32 |
| - |
33 |
| - |
34 |
| -# Adjacency List of Graph |
35 |
| -graph = {0: [1, 2], 1: [3], 2: [3], 3: [4, 5], 4: [], 5: []} |
36 |
| -topological_sort(graph) |
| 44 | + processed_vertices_count += 1 |
| 45 | + topo_order.append(vertex) |
| 46 | + |
| 47 | + # Traverse neighbors |
| 48 | + for neighbor in graph[vertex]: |
| 49 | + indegree[neighbor] -= 1 |
| 50 | + if indegree[neighbor] == 0: |
| 51 | + queue.append(neighbor) |
| 52 | + |
| 53 | + if processed_vertices_count != len(graph): |
| 54 | + return None # no topological ordering exists due to cycle |
| 55 | + return topo_order # valid topological ordering |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == "__main__": |
| 59 | + import doctest |
| 60 | + |
| 61 | + doctest.testmod() |
0 commit comments