Given a Directed Acyclic Graph having V vertices and E edges, find any Topological Sorted ordering of the graph.
Topological Sorted order: It is a linear ordering of vertices such that for every directed edge u -> v, vertex u comes before v in the ordering.
Example:
Input: adj[][] = [[1], [2], [], [2, 4], []]
Output: [0, 3, 1, 4, 2] Explanation: For every pair of vertex(u -> v) in the ordering, u comes before v.
Input: adj[][]= [[1], [2], [3], [], [5], [1, 2]]
Output: [0, 4, 5, 1, 2, 3] Explanation: For every pair of vertex(u -> v) in the ordering, u comes before v.
[Approach]
The idea is to use Kahn’s Algorithm, which applies BFS to generate a valid topological ordering. We first compute the in-degree of every vertex — representing how many incoming edges each vertex has. Then, all vertices with an in-degree of 0 are added to a queue, as they can appear first in the ordering. We repeatedly remove a vertex from the queue, add it to our result list, and reduce the in-degree of all its adjacent vertices. If any of those vertices now have an in-degree of 0, they are added to the queue. This process continues until the queue is empty, and the resulting order represents one valid topological sort of the graph.
Illustration of the algorithm:
Below is the implementation of the above algorithm.
C++
//Driver Code Starts#include<vector>#include<iostream>#include<queue>usingnamespacestd;//Driver Code Endsvector<int>topoSort(vector<vector<int>>&adj){intn=adj.size();vector<int>indegree(n,0);queue<int>q;vector<int>list;// Compute indegreesfor(inti=0;i<n;i++){for(intnext:adj[i])indegree[next]++;}// Add all nodes with indegree 0 // into the queuefor(inti=0;i<n;i++)if(indegree[i]==0)q.push(i);// Kahn’s Algorithm (BFS)while(!q.empty()){inttop=q.front();q.pop();list.push_back(top);for(intnext:adj[top]){indegree[next]--;if(indegree[next]==0)q.push(next);}}returnlist;}//Driver Code StartsvoidaddEdge(vector<vector<int>>&adj,intu,intv){adj[u].push_back(v);}intmain(){intn=6;vector<vector<int>>adj(n);addEdge(adj,0,1);addEdge(adj,1,2);addEdge(adj,2,3);addEdge(adj,4,5);addEdge(adj,5,1);addEdge(adj,5,2);vector<int>res=topoSort(adj);for(intvertex:res)cout<<vertex<<" ";cout<<endl;}//Driver Code Ends
Java
//Driver Code Startsimportjava.util.ArrayList;importjava.util.Queue;importjava.util.LinkedList;classGFG{//Driver Code EndsstaticArrayList<Integer>topoSort(ArrayList<ArrayList<Integer>>adj){intn=adj.size();int[]indegree=newint[n];Queue<Integer>q=newLinkedList<>();ArrayList<Integer>result=newArrayList<>();// Compute indegreesfor(inti=0;i<n;i++){for(intnext:adj.get(i)){indegree[next]++;}}// Add all nodes with indegree 0 // into the queuefor(inti=0;i<n;i++){if(indegree[i]==0){q.add(i);}}// Kahn’s Algorithm (BFS)while(!q.isEmpty()){inttop=q.poll();result.add(top);for(intnext:adj.get(top)){indegree[next]--;if(indegree[next]==0){q.add(next);}}}returnresult;}//Driver Code StartsstaticvoidaddEdge(ArrayList<ArrayList<Integer>>adj,intu,intv){adj.get(u).add(v);}publicstaticvoidmain(String[]args){intn=6;ArrayList<ArrayList<Integer>>adj=newArrayList<>();for(inti=0;i<n;i++){adj.add(newArrayList<>());}addEdge(adj,0,1);addEdge(adj,1,2);addEdge(adj,2,3);addEdge(adj,4,5);addEdge(adj,5,1);addEdge(adj,5,2);ArrayList<Integer>res=topoSort(adj);for(intvertex:res){System.out.print(vertex+" ");}System.out.println();}}//Driver Code Ends
Python
#Driver Code Startsfromcollectionsimportdeque#Driver Code EndsdeftopoSort(adj):n=len(adj)indegree=[0]*nres=[]queue=deque()# Compute indegreesforiinrange(n):fornext_nodeinadj[i]:indegree[next_node]+=1# Add all nodes with indegree 0 # into the queueforiinrange(n):ifindegree[i]==0:queue.append(i)# Kahn’s Algorithmwhilequeue:top=queue.popleft()res.append(top)fornext_nodeinadj[top]:indegree[next_node]-=1ifindegree[next_node]==0:queue.append(next_node)returnresdefaddEdge(adj,u,v):adj[u].append(v)#Driver Code Starts# Examplen=6adj=[[]for_inrange(n)]addEdge(adj,0,1)addEdge(adj,1,2)addEdge(adj,2,3)addEdge(adj,4,5)addEdge(adj,5,1)addEdge(adj,5,2)res=topoSort(adj)print(*res)#Driver Code Ends
C#
//Driver Code StartsusingSystem;usingSystem.Collections.Generic;classGFG{//Driver Code EndspublicstaticList<int>topoSort(List<List<int>>adj){intn=adj.Count;int[]indegree=newint[n];List<int>list=newList<int>();Queue<int>queue=newQueue<int>();// Compute indegreesfor(inti=0;i<n;i++){foreach(intnextinadj[i])indegree[next]++;}// Add all nodes with indegree 0 // into the queuefor(inti=0;i<n;i++)if(indegree[i]==0)queue.Enqueue(i);// Kahn’s Algorithm (BFS)while(queue.Count>0){inttop=queue.Dequeue();list.Add(top);foreach(intnextinadj[top]){indegree[next]--;if(indegree[next]==0)queue.Enqueue(next);}}returnlist;}//Driver Code StartspublicstaticvoidaddEdge(List<List<int>>adj,intu,intv){adj[u].Add(v);}publicstaticvoidMain(){intn=6;List<List<int>>adj=newList<List<int>>();for(inti=0;i<n;i++)adj.Add(newList<int>());addEdge(adj,0,1);addEdge(adj,1,2);addEdge(adj,2,3);addEdge(adj,4,5);addEdge(adj,5,1);addEdge(adj,5,2);List<int>res=topoSort(adj);Console.WriteLine(string.Join(" ",res));}}//Driver Code Ends
JavaScript
functiontopoSort(adj){n=adj.lengthletindegree=newArray(n).fill(0);letqueue=[];letres=[];// Compute indegreesfor(leti=0;i<n;i++){for(letnextofadj[i])indegree[next]++;}// Add all nodes with indegree 0 // into the queuefor(leti=0;i<n;i++){if(indegree[i]===0)queue.push(i);}// Kahn’s Algorithmwhile(queue.length>0){lettop=queue.shift();res.push(top);for(letnextofadj[top]){indegree[next]--;if(indegree[next]===0)queue.push(next);}}returnres;}//Driver Code StartsfunctionaddEdge(adj,u,v){adj[u].push(v);}// Exampleletn=6;letadj=Array.from({length:n},()=>[]);addEdge(adj,0,1);addEdge(adj,1,2);addEdge(adj,2,3);addEdge(adj,4,5);addEdge(adj,5,1);addEdge(adj,5,2);letres=topoSort(adj);console.log(...res);//Driver Code Ends
Output
0 4 5 1 2 3
Time Complexity: O(V+E). For Performing BFS Auxiliary Space: O(V).