Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a Python implementation of the topological sort algorithm using Depth First Search (DFS). #2010

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions DS&Algo Programs in Python/topologicalSort.py
Original file line number Diff line number Diff line change
@@ -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)