Search code examples
c++data-structuresgraph

Topological Sorting using Kahn's Algorithm


I wanted to know ,what does the following part of code mean , I understood the whole function but the for loop at the end is making me confused and not able to understand. So please tell me what it is doing there?

void topologicalSort(vector<int> adj[], int V) 
{ 
    vector<int> in_degree(V, 0); 
  
    for (int u = 0; u < V; u++) { 
        for (int x:adj[u]) 
            in_degree[x]++; 
    } 
  
    queue<int> q; 
    for (int i = 0; i < V; i++) 
        if (in_degree[i] == 0) 
            q.push(i); 

  
    while (!q.empty()) { 
        int u = q.front(); 
        q.pop(); 
        cout<<u<<" "; 
  
        for (int x: adj[u]) 
            if (--in_degree[x] == 0) 
                q.push(x); 
    } 
}

This the link to whole code https://ide.geeksforgeeks.org/PSNw3VplJL


Solution

  • Kahn's algoritm (which has nothing to do with BFS):

    1. Find all the vertexes with in-degree 0 and put them in a queue (q in your code).
    2. Pick a vertex from the queue, output it, and delete it from the graph.
    3. Deleting the vertex will reduce the in-degree of all its neighbors. Some of these could reach in-degree 0 -- put those ones in the queue.
    4. Go back to 2 until you're out of vertexes.

    That last for loop does step (3).