Skip to content

Commit

Permalink
add the Topological function
Browse files Browse the repository at this point in the history
  • Loading branch information
azadsingh3 committed Oct 21, 2024
1 parent 03a4251 commit af2a2aa
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion graphs/depth_first_search_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,25 @@ def dfs_recursive(self, start_vertex: int, visited: list) -> None:
print(" ", end="")
self.dfs_recursive(i, visited)

def topological_sort(self):
visited = set()
stack = []

for vertex in self.vertex:
if vertex not in visited:
self.topological_sort_util(vertex, visited, stack)

return stack[::-1] # Reverse the stack to get the correct order

def topological_sort_util(self, v, visited, stack):
visited.add(v)

for neighbor in self.vertex.get(v, []):
if neighbor not in visited:
self.topological_sort_util(neighbor, visited, stack)

stack.append(v) # Push the vertex to stack


if __name__ == "__main__":
import doctest
Expand All @@ -123,5 +142,5 @@ def dfs_recursive(self, start_vertex: int, visited: list) -> None:
g.add_edge(3, 3)

g.print_graph()
print("DFS:")
print("Topological Sort:", g.topological_sort())
g.dfs()

0 comments on commit af2a2aa

Please sign in to comment.