imashutosh51

Topological sort using DFS

Mar 22nd, 2026
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.04 KB | None | 0 0
  1. '''
  2. Topological sort of an Directed Acyclic graph is the linear order of the vertices such that if there is a node between u & v
  3. then u should come before v in the linear order.
  4.  
  5. Keep one visited array(0,1), and if the node is not visited, call the dfs on that.
  6. Once dfs calling is complete on that node, push it into the stack, In this way, you will push
  7. the lease dependent nodes or last dependent nodes into the stack on the top and stack is your topological sort.
  8. '''
  9.  
  10. def dfs(i,graph,visited,st):
  11.     visited[i]=True
  12.     for neigh in graph[i]:
  13.         if visited[neigh]==False:
  14.             dfs(neigh,graph,visited,st)
  15.     st.append(i)
  16.  
  17. from collections import defaultdict
  18. class Solution:
  19.     def topoSort(self, v, edges):
  20.         visited=[False]*v
  21.         graph=defaultdict(list)
  22.         for a,b in edges:
  23.             graph[a].append(b)
  24.            
  25.         st=[]
  26.         for i in range(v):
  27.             if visited[i]==False:
  28.                 dfs(i,graph,visited,st)
  29.         st.reverse()
  30.         # print(st)
  31.         return st
  32.        
Advertisement
Add Comment
Please, Sign In to add comment