{"id":760,"date":"2024-10-14T14:31:15","date_gmt":"2024-10-14T09:01:15","guid":{"rendered":"https:\/\/codexplained.in\/?p=760"},"modified":"2025-11-24T15:41:37","modified_gmt":"2025-11-24T10:11:37","slug":"topological-sorting-using-dfs-department-of-financial-services","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=760","title":{"rendered":"Topological Sorting using DFS (Department of Financial Services)"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Key Concepts of Topological Sort<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Directed Acyclic Graph (DAG)<\/strong>: Topological sorting can only be applied to DAGs. If the graph has cycles, topological sorting is not possible.<\/li>\n\n\n\n<li><strong>DFS-Based Approach<\/strong>:\n<ul class=\"wp-block-list\">\n<li>Perform DFS traversal on the graph.<\/li>\n\n\n\n<li>Use a stack to keep track of the order of vertices.<\/li>\n\n\n\n<li>After visiting all vertices, the stack will contain the topological sort.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">C Program for Topological Sort Using DFS<\/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\/\/ DFS utility function for topological sort\nvoid topologicalSortUtil(struct Graph* graph, int vertex, int visited&#x5B;], int stack&#x5B;], int* stackIndex) {\n    visited&#x5B;vertex] = 1; \/\/ Mark the current vertex as visited\n\n    \/\/ Recur for all the vertices adjacent to this vertex\n    struct Node* temp = graph-&gt;adjList&#x5B;vertex];\n    while (temp) {\n        int adjVertex = temp-&gt;vertex;\n        if (!visited&#x5B;adjVertex]) {\n            topologicalSortUtil(graph, adjVertex, visited, stack, stackIndex);\n        }\n        temp = temp-&gt;next; \/\/ Move to the next adjacent vertex\n    }\n\n    \/\/ Push current vertex to stack which stores the result\n    stack&#x5B;(*stackIndex)++] = vertex;\n}\n\n\/\/ Function to perform topological sort\nvoid topologicalSort(struct Graph* graph) {\n    int visited&#x5B;MAX] = {0}; \/\/ Array to keep track of visited vertices\n    int stack&#x5B;MAX];         \/\/ Stack to store the topological order\n    int stackIndex = 0;     \/\/ Index for the stack\n\n    \/\/ Call the utility function for each vertex\n    for (int i = 0; i &lt; graph-&gt;numVertices; i++) {\n        if (!visited&#x5B;i]) {\n            topologicalSortUtil(graph, i, visited, stack, &amp;stackIndex);\n        }\n    }\n\n    \/\/ Print the contents of the stack\n    printf(&quot;Topological Sort: &quot;);\n    for (int i = stackIndex - 1; i &gt;= 0; i--) {\n        printf(&quot;%d &quot;, stack&#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, where each vertex points to a list of its neighbors. The <code>Node<\/code> structure is used to represent each vertex&#8217;s adjacent nodes.<\/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>Topological Sort using DFS<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The <code>topologicalSortUtil<\/code> function performs a DFS traversal.<\/li>\n\n\n\n<li>It marks each vertex as visited and recurses through its adjacent vertices.<\/li>\n\n\n\n<li>Once all adjacent vertices are processed, the current vertex is pushed onto a stack.<\/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. Then, we 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<ul class=\"wp-block-list\">\n<li><\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\">Output<\/h4>\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\"><code>Topological Sort: 4 5 0 2 3 1 <br><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>This program demonstrates how to perform topological sorting using DFS on a directed graph. It effectively handles the ordering of vertices to satisfy the prerequisite conditions. You can modify the graph structure by changing the edges to observe different topological sorts. This implementation serves as a good introduction to graph algorithms and their applications in real-world problems, such as scheduling tasks and resolving dependencies.<\/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 Topological Sort C Program for Topological Sort Using DFS 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 Output When you run the program, you will see the following [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":773,"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-760","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/760","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=760"}],"version-history":[{"count":4,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/760\/revisions"}],"predecessor-version":[{"id":1419,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/760\/revisions\/1419"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/773"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=760"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=760"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=760"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}