Kahn's Algorithm (Topological Sort using BFS)

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):
    
        indegree=[0 for i in range(n)]
        # Fill the indegree array
        for i in range(len(adj)):
            for j in range(len(adj[i])):
                indegree[adj[i][j]]+=1
        q=[]
        ans=[]
        # Fill the queue with vertices 
        # having 0 indegree
        for i in range(n):
            if(indegree[i]==0):
                q.insert(0,i)
       
        # BFS 
        while(len(q)>0):
            for _ in range(len(q)):
                node=q.pop()
                ans.append(node)
                for i in adj[node]:
                    indegree[i]-=1
                    if(indegree[i]==0):
                        q.insert(0,i)
        return ans

Last updated