Topological Sort
Works only on Directed Acyclic Graphs(DAG)
Problem Link: https://practice.geeksforgeeks.org/problems/topological-sort/1
class Solution:
#Function to return list containing vertices in Topological order.
def topoSort(self, n, adj):
# Code here
def dfs(idx,visited,adj):
visited[idx]=1
for i in adj[idx]:
if(visited[i]==0):
dfs(i,visited,adj)
# If DFS is completed for a node,
# put it into the stack
s.append(idx)
visited=[0 for i in range(n)]
s=[]
for i in range(n):
if(visited[i]==0):
dfs(i,visited,adj)
# Reverse the stack and return it
s=s[::-1]
return s
PreviousRestore the Array From Adjacent Pairs (Leetcode 1743)NextKahn's Algorithm (Topological Sort using BFS)
Last updated