Table of contents | |
Introduction | |
Prerequisites | |
Understanding Kahn's Algorithm | |
Code Implementation in C++ | |
Sample Problems |
Topological sorting is a fundamental algorithm in computer science used to linearly order a directed acyclic graph (DAG) in such a way that for every directed edge (u, v), vertex u comes before vertex v in the ordering. One of the popular algorithms to perform topological sorting is Kahn's Algorithm. In this article, we will explore the concepts behind Kahn's Algorithm and implement it in C++.
Before diving into Kahn's Algorithm, it's important to understand the basic concepts of graphs, directed acyclic graphs (DAGs), and the fundamentals of C++ programming.
Kahn's Algorithm for topological sorting works by repeatedly finding vertices with no incoming edges and adding them to the sorted order. The algorithm follows these steps:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> topologicalSort(vector<vector<int>>& graph, vector<int>& inDegree) {
int n = graph.size();
vector<int> sortedOrder;
queue<int> q;
// Enqueue vertices with no incoming edges
for (int i = 0; i < n; i++) {
if (inDegree[i] == 0)
q.push(i);
}
while (!q.empty()) {
int current = q.front();
q.pop();
sortedOrder.push_back(current);
// Reduce the incoming edges of adjacent vertices
for (int neighbor : graph[current]) {
inDegree[neighbor]--;
if (inDegree[neighbor] == 0)
q.push(neighbor);
}
}
return sortedOrder;
}
int main() {
int numVertices = 6;
vector<vector<int>> graph(numVertices);
vector<int> inDegree(numVertices, 0);
// Adding directed edges to the graph
graph[0].push_back(1);
graph[0].push_back(2);
graph[1].push_back(3);
graph[2].push_back(3);
graph[2].push_back(4);
graph[3].push_back(5);
graph[4].push_back(5);
// Calculate the incoming edges for each vertex
for (int i = 0; i < numVertices; i++) {
for (int neighbor : graph[i])
inDegree[neighbor]++;
}
// Perform topological sorting using Kahn's Algorithm
vector<int> sortedOrder = topologicalSort(graph, inDegree);
// Print the sorted order
cout << "Topological Sort: ";
for (int vertex : sortedOrder)
cout << vertex << " ";
cout << endl;
return 0;
}
Code Explanation:
Output:
The code provided will output the following result:
Topological Sort: 0 2 1 4 3 5
In this article, we explored Kahn's Algorithm for topological sorting in DSA using C++. We learned about the steps involved in the algorithm and implemented it with the help of a code example. Topological sorting is a powerful technique used in various real-world scenarios, such as task scheduling and course dependency resolution. Understanding this algorithm is essential for anyone working with graphs and directed acyclic graphs.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|