Kahn’s Algorithm in C Language
Last Updated :
10 Jul, 2024
In this post, we will see the implementation of Kahn's Algorithm in C language.
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 directed edge u→v vertex u comes before v. This algorithm is particularly useful in scenarios like task scheduling course prerequisite structures and resolving the symbol dependencies in linkers.
How does Kahn’s Algorithm work in C language?
The algorithm works by repeatedly finding vertices with no incoming edges, removing them from the graph, and updating the incoming edges of the remaining vertices. This process continues until all vertices have been ordered.
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.
C Program to Implement Kahn's Algorithm
Here's a C program that implements Kahn's Algorithm for the topological sorting:
C
// C program to implement Kahn's Algorithm
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
// Structure to represent a graph
struct Graph {
// Number of vertices in the graph
int V;
// Adjacency matrix representation of the graph
int adj[MAX][MAX];
};
// Function to create a graph with V vertices
struct Graph* createGraph(int V)
{
// Allocate memory for the graph structure
struct Graph* graph
= (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V; // Set the number of vertices
// Initialize the adjacency matrix to 0
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
graph->adj[i][j] = 0;
return graph;
}
// Function to add an edge to the graph
void addEdge(struct Graph* graph, int u, int v)
{
// Set the edge from u to v
graph->adj[u][v] = 1;
}
// Function to perform Kahn's Algorithm for Topological
// Sorting
void kahnTopologicalSort(struct Graph* graph)
{
// Array to store in-degrees of all vertices
int in_degree[MAX] = { 0 };
// Compute in-degrees of all vertices
for (int i = 0; i < graph->V; i++)
for (int j = 0; j < graph->V; j++)
if (graph->adj[i][j])
in_degree[j]++;
// Enqueue vertices with zero in-degrees
int queue[MAX], front = 0, rear = 0;
for (int i = 0; i < graph->V; i++)
if (in_degree[i] == 0)
queue[rear++] = i;
// Count of visited vertices
int count = 0;
// Array to store topological order
int top_order[MAX];
// Process vertices in the queue
while (front < rear) {
int u = queue[front++];
top_order[count++] = u;
// Reduce in-degrees of adjacent vertices
for (int i = 0; i < graph->V; i++) {
if (graph->adj[u][i]) {
if (--in_degree[i] == 0)
queue[rear++] = i;
}
}
}
// Check if there was a cycle in the graph
if (count != graph->V) {
printf("There exists a cycle in the graph\n");
return;
}
// Print the topological order
for (int i = 0; i < count; i++)
printf("%d ", top_order[i]);
printf("\n");
}
int main()
{
// Create a graph with 6 vertices
struct Graph* graph = createGraph(6);
// Add edges to the graph
addEdge(graph, 5, 2);
addEdge(graph, 5, 0);
addEdge(graph, 4, 0);
addEdge(graph, 4, 1);
addEdge(graph, 2, 3);
addEdge(graph, 3, 1);
// Perform and print topological sort
printf("Topological Sort of the given graph:\n");
kahnTopologicalSort(graph);
return 0;
}
OutputTopological Sort of the given graph:
4 5 0 2 3 1
Working example of Kahn's Algorithm in C
Given a Directed Acyclic Graph having V vertices and E edges, your task is to find any Topological Sorted order of the graph using Kahn's Algorithm in C language.
V = 6, E = ((5, 2), (5, 0), (4, 0), (4, 1), (2, 3), (3, 1));
- Initialize in-degrees:
- in_degree = [2, 2, 1, 1, 0, 0]
- Queue initialization:
- Vertices 4 and 5 have zero in-degrees so queue = [4, 5]
- Process the queue:
- Dequeue 4, topological_order = [4]
- Decrease in-degrees of the 0 and 1: in_degree = [1, 1, 1, 1, 0, 0]
- Enqueue 1: queue = [5, 0, 1]
- Repeat for the all vertices...
- Final topological order:
Complexity Analysis of Kahn's Algorithm in C
Time Complexity: O(V+E) where V is the number of the vertices and E is the number of the edges. This is because each vertex and edge is processed exactly once.
Space Complexity: O(V) primarily for the storing the in-degree array, queue and topological order.
Similar Reads
Kahnâs Algorithm in C++ 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, v
4 min read
Tarjanâs Algorithm in C Language In this post, we will see the implementation of Tarjan's Algorithm in C language.What is Tarjan's Algorithm?Tarjan'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 oth
5 min read
Kosarajuâs Algorithm in C Kosarajuâs Algorithm is a method by which we can use to find all strongly connected components (SCCs) in a directed graph. This algorithm has application in various applications such as finding cycles in a graph, understanding the structure of the web, and analyzing networks.In this article, we will
5 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
Shortest Path Algorithm in C In C programming, finding the shortest path between nodes in a graph is a common and crucial problem with applications in various fields such as networking, transportation, and logistics. Shortest path algorithms are designed to find the most efficient route from a starting node to a destination nod
15+ min read
Johnson Algorithm in C Johnson's Algorithm is an efficient algorithm used to find the shortest paths between all pairs of vertices in a weighted graph. It works even for graphs with negative weights, provided there are no negative weight cycles. This algorithm is particularly useful for sparse graphs and combines both Dij
5 min read