|
| 1 | +"""Topological Sort on Directed Acyclic Graph(DAG)""" |
| 2 | + |
| 3 | +# a |
| 4 | +# / \ |
| 5 | +# b c |
| 6 | +# / \ |
| 7 | +# d e |
| 8 | + |
1 | 9 | edges: dict[str, list[str]] = {
|
2 | 10 | "a": ["c", "b"],
|
3 | 11 | "b": ["d", "e"],
|
4 | 12 | "c": [],
|
5 | 13 | "d": [],
|
6 | 14 | "e": [],
|
7 | 15 | }
|
| 16 | + |
8 | 17 | vertices: list[str] = ["a", "b", "c", "d", "e"]
|
9 | 18 |
|
| 19 | +# Perform topological sort on a DAG starting from the specified node |
10 | 20 | def topological_sort(start: str, visited: list[str], sort: list[str]) -> list[str]:
|
11 |
| - visited.append(start) |
12 | 21 | current = start
|
13 |
| - for neighbor in edges[start]: |
| 22 | + # Mark the current node as visited |
| 23 | + visited.append(current) |
| 24 | + # List of all neighbors of current node |
| 25 | + neighbors = edges[current] |
| 26 | + |
| 27 | + # Traverse all neighbors of the current node |
| 28 | + for neighbor in neighbors: |
| 29 | + # Recursively visit each unvisited neighbor |
14 | 30 | if neighbor not in visited:
|
15 |
| - topological_sort(neighbor, visited, sort) |
| 31 | + sort = topological_sort(neighbor, visited, sort) |
| 32 | + |
| 33 | + # After visiting all neighbors, add the current node to the sorted list |
16 | 34 | sort.append(current)
|
| 35 | + |
| 36 | + # If there are some nodes that were not visited (disconnected components) |
| 37 | + if len(visited) != len(vertices): |
| 38 | + for vertex in vertices: |
| 39 | + if vertex not in visited: |
| 40 | + sort = topological_sort(vertex, visited, sort) |
| 41 | + |
| 42 | + # Return sorted list |
17 | 43 | return sort
|
18 | 44 |
|
19 | 45 | if __name__ == "__main__":
|
| 46 | + # Topological Sorting from node "a" (Returns the order in bottom up approach) |
20 | 47 | sort = topological_sort("a", [], [])
|
21 |
| - sort.reverse() #Top down approach |
| 48 | + |
| 49 | + # Reversing the list to get the correct topological order (Top down approach) |
| 50 | + sort.reverse() |
22 | 51 | print(sort)
|
0 commit comments