Skip to content

Commit af2a2aa

Browse files
committed
add the Topological function
1 parent 03a4251 commit af2a2aa

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

graphs/depth_first_search_2.py

+20-1
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,25 @@ def dfs_recursive(self, start_vertex: int, visited: list) -> None:
108108
print(" ", end="")
109109
self.dfs_recursive(i, visited)
110110

111+
def topological_sort(self):
112+
visited = set()
113+
stack = []
114+
115+
for vertex in self.vertex:
116+
if vertex not in visited:
117+
self.topological_sort_util(vertex, visited, stack)
118+
119+
return stack[::-1] # Reverse the stack to get the correct order
120+
121+
def topological_sort_util(self, v, visited, stack):
122+
visited.add(v)
123+
124+
for neighbor in self.vertex.get(v, []):
125+
if neighbor not in visited:
126+
self.topological_sort_util(neighbor, visited, stack)
127+
128+
stack.append(v) # Push the vertex to stack
129+
111130

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

125144
g.print_graph()
126-
print("DFS:")
145+
print("Topological Sort:", g.topological_sort())
127146
g.dfs()

0 commit comments

Comments
 (0)