Kahn’s Algorithm in C++ Last Updated : 01 Aug, 2024 Comments Improve Suggest changes 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++ dasrudra0710 Follow Improve Article Tags : C++ CPP-DSA Practice Tags : CPP Similar Reads Johnson Algorithm in C++ Johnsonâs Algorithm is an algorithm used to find the shortest paths between all pairs of vertices in a weighted graph. It is especially useful for sparse graphs and can handle negative weights, provided there are no negative weight cycles. This algorithm uses both Bellman-Ford and Dijkstra's algorit 8 min read Kosarajuâs Algorithm in C++ In this post, we will see the implementation of Kosarajuâs Algorithm in C++.What is Kosarajuâs Algorithm?Kosarajuâs Algorithm is a classic algorithm used for finding strongly connected components (SCCs) in a directed graph. An SCC is a maximal subgraph where every vertex is reachable from every othe 4 min read Kahnâs Algorithm in C Language In this post, we will see the implementation of Kahn's Algorithm in C language.What is Kahn's Algorithm?The Kahn's Algorithm is a classic algorithm used to the perform the topological sorting on the Directed Acyclic Graph (DAG). It produces a linear ordering of the vertices such that for every direc 5 min read Convex Hull Algorithm in C++ The Convex Hull problem is fundamental problem in computational geometry. In this, we need to find the smallest convex polygon, known as the convex hull, that can include a given set of points in a two-dimensional plane. This problem has various applications in areas such as computer graphics, geogr 15+ min read Floyd-Warshall Algorithm in C++ The Floyd-Warshall algorithm is a dynamic programming technique used to find the shortest paths between all pairs of vertices in a weighted graph. This algorithm is particularly useful for graphs with dense connections and can handle both positive and negative edge weights, though it cannot handle n 4 min read Algorithm Library Functions in C++ STL Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Fin 4 min read Implementation of Rabin Karp Algorithm in C++ The Rabin-Karp Algorithm is a string-searching algorithm that efficiently finds a pattern within a text using hashing. It is particularly useful for finding multiple patterns in the same text or for searching in streams of data. In this article, we will learn how to implement the Rabin-Karp Algorith 5 min read Implementation of Wu Manber Algorithm? What is Wu- Manber Algorithm? The Wu-Manber algorithm is a string-matching algorithm that is used to efficiently search for patterns in a body of text. It is a hybrid algorithm that combines the strengths of the Boyer-Moore and Knuth-Morris-Pratt algorithms to provide fast and accurate pattern match 12 min read Boyer-Moore Algorithm for Pattern Searching in C++ The Boyer-Moore algorithm is an efficient string searching algorithm that is used to find occurrences of a pattern within a text. This algorithm preprocesses the pattern and uses this information to skip sections of the text, making it much faster than simpler algorithms like the naive approach.In t 6 min read boost::algorithm::one_of_equal() in C++ library The one_of_equal() function in C++ boost library is found under the header 'boost/algorithm/cxx11/one_of.hpp' which tests if exactly one of the elements of a sequence against the value passed is same. It takes a sequence and a value, and returns true if the exactly one of the elements are same in th 2 min read Like