{"id":660,"date":"2024-10-10T13:39:37","date_gmt":"2024-10-10T08:09:37","guid":{"rendered":"https:\/\/codexplained.in\/?p=660"},"modified":"2025-11-24T15:58:49","modified_gmt":"2025-11-24T10:28:49","slug":"find-strongly-connected-components-kosarajus-algorithm","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=660","title":{"rendered":"Find Powerfully Connected Components using Kosaraju\u2019s Algorithm"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Overview of Kosaraju\u2019s Algorithm<\/h3>\n\n\n\n<p>Kosaraju&#8217;s algorithm is a two-pass method to find all strongly connected components in a directed graph. A strongly connected component is a maximal subgraph where every vertex is reachable from every other vertex in that component.<\/p>\n\n\n\n<p><strong>Steps of the algorithm:<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>First Pass (DFS on original graph):<\/strong>\n<ul class=\"wp-block-list\">\n<li>Perform a Depth-First Search (DFS) on the original graph to determine the finish order of nodes.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Transpose the Graph:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Reverse the direction of all edges in the graph.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Second Pass (DFS on transposed graph):<\/strong>\n<ul class=\"wp-block-list\">\n<li>Perform DFS on the transposed graph in the order of decreasing finish times obtained from the first pass. Each DFS call will identify one strongly connected component.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Implementation in C<\/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 to represent a graph\nstruct Graph {\n    int V;            \/\/ Number of vertices\n    int adj&#x5B;MAX]&#x5B;MAX]; \/\/ Adjacency matrix\n};\n\n\/\/ Stack structure for DFS\nint stack&#x5B;MAX], top = -1;\n\n\/\/ Function to push element onto stack\nvoid push(int vertex) {\n    stack&#x5B;++top] = vertex;\n}\n\n\/\/ Function to pop element from stack\nint pop() {\n    return stack&#x5B;top--];\n}\n\n\/\/ Function to initialize the graph\nstruct Graph* createGraph(int vertices) {\n    struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));\n    graph-&gt;V = vertices;\n    for (int i = 0; i &lt; vertices; i++)\n        for (int j = 0; j &lt; vertices; j++)\n            graph-&gt;adj&#x5B;i]&#x5B;j] = 0; \/\/ Initialize adjacency matrix\n    return graph;\n}\n\n\/\/ Function to add an edge to the graph\nvoid addEdge(struct Graph* graph, int src, int dest) {\n    graph-&gt;adj&#x5B;src]&#x5B;dest] = 1; \/\/ Directed edge from src to dest\n}\n\n\/\/ DFS function to fill the stack with vertices\nvoid dfs(struct Graph* graph, int vertex, int visited&#x5B;]) {\n    visited&#x5B;vertex] = 1;\n    for (int i = 0; i &lt; graph-&gt;V; i++) {\n        if (graph-&gt;adj&#x5B;vertex]&#x5B;i] == 1 &amp;&amp; !visited&#x5B;i]) {\n            dfs(graph, i, visited);\n        }\n    }\n    push(vertex); \/\/ Push vertex to stack after exploring all its neighbors\n}\n\n\/\/ Transpose the graph\nstruct Graph* transposeGraph(struct Graph* graph) {\n    struct Graph* transposed = createGraph(graph-&gt;V);\n    for (int i = 0; i &lt; graph-&gt;V; i++) {\n        for (int j = 0; j &lt; graph-&gt;V; j++) {\n            if (graph-&gt;adj&#x5B;i]&#x5B;j] == 1) {\n                addEdge(transposed, j, i); \/\/ Reverse the edge\n            }\n        }\n    }\n    return transposed;\n}\n\n\/\/ DFS to find strongly connected components\nvoid dfsTransposed(struct Graph* transposed, int vertex, int visited&#x5B;]) {\n    visited&#x5B;vertex] = 1;\n    printf(&quot;%d &quot;, vertex); \/\/ Print the vertex in the component\n    for (int i = 0; i &lt; transposed-&gt;V; i++) {\n        if (transposed-&gt;adj&#x5B;vertex]&#x5B;i] == 1 &amp;&amp; !visited&#x5B;i]) {\n            dfsTransposed(transposed, i, visited);\n        }\n    }\n}\n\n\/\/ Function to find and print all strongly connected components\nvoid findSCCs(struct Graph* graph) {\n    int visited&#x5B;MAX] = {0};\n    \n    \/\/ First pass - fill vertices in stack according to finish time\n    for (int i = 0; i &lt; graph-&gt;V; i++) {\n        if (!visited&#x5B;i]) {\n            dfs(graph, i, visited);\n        }\n    }\n\n    \/\/ Transpose the graph\n    struct Graph* transposed = transposeGraph(graph);\n\n    \/\/ Second pass - process all vertices in order defined by the stack\n    for (int i = 0; i &lt; graph-&gt;V; i++) visited&#x5B;i] = 0; \/\/ Reset visited array\n    \n    printf(&quot;Strongly Connected Components:\\n&quot;);\n    while (top != -1) {\n        int vertex = pop();\n        if (!visited&#x5B;vertex]) {\n            printf(&quot;Component: &quot;);\n            dfsTransposed(transposed, vertex, visited);\n            printf(&quot;\\n&quot;);\n        }\n    }\n}\n\n\/\/ Main function\nint main() {\n    struct Graph* graph = createGraph(5); \/\/ Create a graph with 5 vertices\n    addEdge(graph, 0, 1);\n    addEdge(graph, 1, 2);\n    addEdge(graph, 2, 0);\n    addEdge(graph, 1, 3);\n    addEdge(graph, 3, 4);\n\n    findSCCs(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 matrix. We define a <code>Graph<\/code> structure to hold the number of vertices and the adjacency matrix.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Stack Operations:<\/strong>\n<ul class=\"wp-block-list\">\n<li>We use a simple stack to store vertices based on their finishing times during DFS.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>DFS Implementation:<\/strong>\n<ul class=\"wp-block-list\">\n<li>The <code>dfs<\/code> function explores each vertex and pushes it onto the stack after exploring its neighbors.<\/li>\n\n\n\n<li>The <code>dfsTransposed<\/code> function performs DFS on the transposed graph and prints the vertices of each strongly connected component.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Transposing the Graph:<\/strong>\n<ul class=\"wp-block-list\">\n<li>The <code>transposeGraph<\/code> function creates a new graph where all edges are reversed.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Finding SCCs:<\/strong>\n<ul class=\"wp-block-list\">\n<li>In the <code>findSCCs<\/code> function, we first fill the stack using a DFS on the original graph, transpose the graph, and then use another DFS based on the stack to identify and print each SCC.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input Edges<br><\/strong>In the main function, the following edges are added to the graph:<br><br>addEdge(graph, 0, 1); \/\/ Edge from vertex 0 to vertex 1<br>addEdge(graph, 1, 2); \/\/ Edge from vertex 1 to vertex 2<br>addEdge(graph, 2, 0); \/\/ Edge from vertex 2 to vertex 0 (forming a cycle)<br>addEdge(graph, 1, 3); \/\/ Edge from vertex 1 to vertex 3<br>addEdge(graph, 3, 4); \/\/ Edge from vertex 3 to vertex 4<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Output<\/h3>\n\n\n\n<p>When you run the program, you should expect the output to look something like this:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">yamlCopy code<code>Strongly Connected Components:\nComponent: 4 \nComponent: 3 \nComponent: 2 1 0 \n<\/code><\/pre>\n\n\n\n<p>This output shows the strongly connected components of the given directed graph. Each component is printed separately.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>Kosaraju\u2019s algorithm is efficient and elegant for finding SCCs in directed graphs. By understanding the two-pass DFS and the importance of graph transposition, we can effectively break down complex graphs into their strongly connected components.<\/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>Overview of Kosaraju\u2019s Algorithm Kosaraju&#8217;s algorithm is a two-pass method to find all strongly connected components in a directed graph. A strongly connected component is a maximal subgraph where every vertex is reachable from every other vertex in that component. Steps of the algorithm: Implementation in C Explanation of the Code Input EdgesIn the main [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":661,"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-660","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\/660","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=660"}],"version-history":[{"count":7,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/660\/revisions"}],"predecessor-version":[{"id":1469,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/660\/revisions\/1469"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/661"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=660"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=660"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=660"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}