Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
Kahn’s Algorithm in C++
Next article icon

Kahn’s Algorithm in C Language

Last Updated : 10 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 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.

Table of Content

  • What is Kahn's Algorithm?
  • How does Kahn’s Algorithm work in C language?
  • Steps of Kahn's Algorithm to implement in C:
  • C Program to Implement Kahn's Algorithm
  • Working example of Kahn's Algorithm in C:
  • Complexity Analysis of Kahn's Algorithm in C

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; } 

Output
Topological 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:
    • [4, 5, 2, 0, 3, 1]

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.


Next Article
Kahn’s Algorithm in C++

M

mguru4c05q
Improve
Article Tags :
  • C Language
  • C-DSA

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,
    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 ot
    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 wil
    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 oth
    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
  • 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
  • Prim's Algorithm in C
    Prim’s algorithm is a greedy algorithm that finds the minimum spanning tree (MST) for a weighted undirected graph. It starts with a single vertex and grows the MST one edge at a time by adding the smallest edge that connects a vertex in the MST to a vertex outside the MST. In this article, we will l
    6 min read
  • Convex Hull Algorithm in C
    The Convex Hull problem is a fundamental computational geometry problem, where the goal is to find the smallest convex polygon called convex hull that can enclose a set of points in a 2D plane. This problem has various applications, such as in computer graphics, geographic information systems, and c
    15+ min read
  • Floyd-Warshall Algorithm in C
    Floyd-Warshall algorithm is a dynamic programming algorithm used to find the shortest paths between all pairs of vertices in a weighted graph. It works for both directed and undirected graphs and can handle negative weights, provided there are no negative weight cycles. In this article, we will lear
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences