Kahn’s Algorithm in C++ Last Updated : 01 Aug, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report In this post, we will see the implementation of Kahn’s Algorithm in C++.What is Kahn’s Algorithm?Kahn’s Algorithm is a classic algorithm used for topological sorting of a directed acyclic graph (DAG). Topological sorting is a linear ordering of vertices such that for every directed edge u -> v, vertex u comes before v in the ordering. This algorithm is widely used in various applications such as scheduling tasks, course prerequisite ordering, and resolving symbol dependencies in linkers.How does Kahn’s Algorithm work in C++?The algorithm works by repeatedly removing nodes with no incoming edges and adding them to the topological order. By removing nodes with no incoming edges, the graph reduces in size until all nodes are processed.Steps of Kahn’s Algorithm to Implement in C++Add all nodes with in-degree 0 to a queue.While the queue is not empty:Remove a node from the queue.For each outgoing edge from the removed node, decrement the in-degree of the destination node by 1.If the in-degree of a destination node becomes 0, add it to the queue.If the queue is empty and there are still nodes in the graph, the graph contains a cycle and cannot be topologically sorted.The nodes in the queue represent the topological ordering of the graph.Working of Kahn’s Algorithm in C++The below example illustrates a step-by-step implementation of Kahn’s Algorithm.C++ Program to Implement Kahn’s AlgorithmBelow is a C++ program that implements Kahn’s Algorithm for topological sorting: C++ // C++ program to implement Kahn’s Algorithm #include <iostream> #include <queue> #include <vector> using namespace std; // Function to return list containing vertices in // Topological order vector<int> topologicalSort(vector<vector<int> >& adj, int V) { // Vector to store indegree of each vertex vector<int> indegree(V); // Calculating indegree for each vertex for (int i = 0; i < V; i++) { for (auto it : adj[i]) { indegree[it]++; } } // Queue to store vertices with indegree 0 queue<int> q; // Pushing vertices with indegree 0 to the queue for (int i = 0; i < V; i++) { if (indegree[i] == 0) { q.push(i); } } // Vector to store the result vector<int> result; // Performing topological sort while (!q.empty()) { // Get the front element from the queue int node = q.front(); q.pop(); // Add it to the result result.push_back(node); // Decrease indegree of adjacent vertices as the // current node is in topological order for (auto it : adj[node]) { indegree[it]--; // If indegree becomes 0, push it to the queue if (indegree[it] == 0) { q.push(it); } } } // Check for cycle if (result.size() != V) { // If result size is not equal to number of // vertices, graph contains a cycle cout << "Graph contains cycle!" << endl; return {}; } // Return the topological order return result; } int main() { // Number of nodes int n = 6; // Edges vector<vector<int> > edges = { { 0, 1 }, { 1, 2 }, { 2, 3 }, { 4, 5 }, { 5, 1 }, { 5, 2 } }; // Graph represented as an adjacency list vector<vector<int> > adj(n); // Constructing adjacency list for (auto i : edges) { adj[i[0]].push_back(i[1]); } // Performing topological sort cout << "Topological sorting of the graph: "; vector<int> result = topologicalSort(adj, n); // Displaying result for (auto i : result) { cout << i << " "; } return 0; } OutputTopological sorting of the graph: 0 4 5 1 2 3 Time Complexity: O(V+E), The outer for loop will be executed V number of times and the inner for loop will be executed E number of times.Auxiliary Space: O(V), The queue needs to store all the vertices of the graph. So the space required is O(V)Applications of Kahn’sAlgorithmCourses at universities frequently have prerequisites for other courses. The courses can be scheduled using Kahn’s algorithm so that the prerequisites are taken before the courses that call for them.When developing software, libraries and modules frequently rely on other libraries and modules. The dependencies can be installed in the proper order by using Kahn’s approach.In project management, activities frequently depend on one another. The tasks can be scheduled using Kahn’s method so that the dependent tasks are finished before the tasks that depend on them.In data processing pipelines, the outcomes of some processes may be dependent. The stages can be carried out in the right order by using Kahn’s algorithm.In the creation of an electronic circuit, some components may be dependent on the output of others. The components can be joined in the right order by using Kahn’s technique. Comment More infoAdvertise with us Next Article Kahn’s Algorithm in C++ D dasrudra0710 Follow Improve Article Tags : C++ CPP-DSA Practice Tags : CPP Similar Reads C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to 5 min read Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance 10 min read Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th 5 min read Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact 12 min read 3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power 13 min read Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and 9 min read 30 OOPs Interview Questions and Answers [2025 Updated] Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is 15 min read What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac 13 min read Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca 7 min read Like