diff --git a/DS&Algo Programs in Python/topologicalSort.py b/DS&Algo Programs in Python/topologicalSort.py new file mode 100644 index 000000000..b68092fb6 --- /dev/null +++ b/DS&Algo Programs in Python/topologicalSort.py @@ -0,0 +1,37 @@ +#Everyone feels topo sort is hard, just look at this code and try to understand it. And all set!!! +from collections import defaultdict + +class Graph: + def __init__(self, vertices): + self.graph = defaultdict(list) + self.V = vertices + + def add_edge(self, u, v): + self.graph[u].append(v) + + def topological_sort_util(self, v, visited, stack): + visited[v] = True + for i in self.graph[v]: + if visited[i] == False: + self.topological_sort_util(i, visited, stack) + stack.append(v) + + def topological_sort(self): + visited = [False] * self.V + stack = [] + for i in range(self.V): + if visited[i] == False: + self.topological_sort_util(i, visited, stack) + return stack[::-1] + +# Example usage: +g = Graph(6) +g.add_edge(5, 2) +g.add_edge(5, 0) +g.add_edge(4, 0) +g.add_edge(4, 1) +g.add_edge(2, 3) +g.add_edge(3, 1) + +result = g.topological_sort() +print("Topological Sort:", result)