My issue
please help me…give solution to this question
My code
from collections import defaultdict
def topological_sort_dfs(graph, node, visited, stack):
visited[node] = True
for neighbor in graph[node]:
if not visited[neighbor]:
topological_sort_dfs(graph, neighbor, visited, stack)
stack.append(node)
def topological_sort(V, edges):
graph = defaultdict(list)
for edge in edges:
u, v = edge
graph[u].append(v)
visited = [False] * V
stack = []
for i in range(V):
if not visited[i]:
topological_sort_dfs(graph, i, visited, stack)
return stack[::-1]
# Example usage
test_cases = 2
inputs = [(2, [(0, 1), (0, 3), (1, 2)]), (4, [(0, 1), (0, 3), (1, 2), (3, 2)])]
for V, edges in inputs:
result = topological_sort(V, edges)
print(*result)
Learning course: Analysis and Design of Algorithms
Problem Link: Topological sort in Analysis and Design of Algorithms