Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Topological sort of an Directed Acyclic graph is the linear order of the vertices such that if there is a node between u & v
- then u should come before v in the linear order.
- Keep one visited array(0,1), and if the node is not visited, call the dfs on that.
- Once dfs calling is complete on that node, push it into the stack, In this way, you will push
- the lease dependent nodes or last dependent nodes into the stack on the top and stack is your topological sort.
- '''
- def dfs(i,graph,visited,st):
- visited[i]=True
- for neigh in graph[i]:
- if visited[neigh]==False:
- dfs(neigh,graph,visited,st)
- st.append(i)
- from collections import defaultdict
- class Solution:
- def topoSort(self, v, edges):
- visited=[False]*v
- graph=defaultdict(list)
- for a,b in edges:
- graph[a].append(b)
- st=[]
- for i in range(v):
- if visited[i]==False:
- dfs(i,graph,visited,st)
- st.reverse()
- # print(st)
- return st
Advertisement
Add Comment
Please, Sign In to add comment