{"id":607,"date":"2024-10-10T13:43:38","date_gmt":"2024-10-10T08:13:38","guid":{"rendered":"https:\/\/codexplained.in\/?p=607"},"modified":"2025-11-24T15:56:03","modified_gmt":"2025-11-24T10:26:03","slug":"find-connected-components-in-graph","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=607","title":{"rendered":"Find Connected Components in Graph"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Understanding Connected Components<\/h3>\n\n\n\n<p>In graph theory, a connected component is a subset of vertices such that there is a path between any two vertices in this subset. In simpler terms, it means that you can travel between any two nodes in that subset without leaving it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Approach<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Graph Representation<\/strong>: We will represent the graph using an adjacency list.<\/li>\n\n\n\n<li><strong>DFS\/BFS Traversal<\/strong>: We can use Depth First Search (DFS) or Breadth First Search (BFS) to explore the graph and find connected components.<\/li>\n\n\n\n<li><strong>Visited Array<\/strong>: We need to keep track of visited nodes to avoid counting them multiple times.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Implementation Steps<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Read the number of vertices and edges.<\/li>\n\n\n\n<li>Construct the adjacency list.<\/li>\n\n\n\n<li>Initialize a visited array.<\/li>\n\n\n\n<li>Traverse each vertex. If it&#8217;s not visited, perform a DFS\/BFS starting from that vertex and mark all reachable vertices.<\/li>\n\n\n\n<li>Count each time you start a new traversal as a new connected component.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">C Code<\/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_VERTICES 100\n\n\/\/ Structure to represent a node in the adjacency list\nstruct Node {\n    int vertex;\n    struct Node* next;\n};\n\n\/\/ Graph structure\nstruct Graph {\n    int numVertices;\n    struct Node** adjLists;\n};\n\n\/\/ Function to create a graph\nstruct Graph* createGraph(int vertices) {\n    struct Graph* graph = malloc(sizeof(struct Graph));\n    graph-&gt;numVertices = vertices;\n    graph-&gt;adjLists = malloc(vertices * sizeof(struct Node*));\n\n    for (int i = 0; i &lt; vertices; i++) {\n        graph-&gt;adjLists&#x5B;i] = NULL;\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    \/\/ Add edge from src to dest\n    struct Node* newNode = malloc(sizeof(struct Node));\n    newNode-&gt;vertex = dest;\n    newNode-&gt;next = graph-&gt;adjLists&#x5B;src];\n    graph-&gt;adjLists&#x5B;src] = newNode;\n\n    \/\/ Since the graph is undirected, add an edge from dest to src\n    newNode = malloc(sizeof(struct Node));\n    newNode-&gt;vertex = src;\n    newNode-&gt;next = graph-&gt;adjLists&#x5B;dest];\n    graph-&gt;adjLists&#x5B;dest] = newNode;\n}\n\n\/\/ Depth First Search function\nvoid DFS(struct Graph* graph, int vertex, int* visited) {\n    visited&#x5B;vertex] = 1; \/\/ Mark the vertex as visited\n    printf(&quot;%d &quot;, vertex);\n\n    struct Node* temp = graph-&gt;adjLists&#x5B;vertex];\n    while (temp) {\n        int connectedVertex = temp-&gt;vertex;\n        if (!visited&#x5B;connectedVertex]) {\n            DFS(graph, connectedVertex, visited);\n        }\n        temp = temp-&gt;next;\n    }\n}\n\n\/\/ Function to find and print connected components\nvoid findConnectedComponents(struct Graph* graph) {\n    int* visited = malloc(graph-&gt;numVertices * sizeof(int));\n    for (int i = 0; i &lt; graph-&gt;numVertices; i++) {\n        visited&#x5B;i] = 0; \/\/ Initialize all vertices as not visited\n    }\n\n    printf(&quot;Connected components:\\n&quot;);\n    for (int i = 0; i &lt; graph-&gt;numVertices; i++) {\n        if (!visited&#x5B;i]) {\n            printf(&quot;Component: &quot;);\n            DFS(graph, i, visited);\n            printf(&quot;\\n&quot;);\n        }\n    }\n\n    free(visited);\n}\n\n\/\/ Main function\nint main() {\n    int vertices, edges, src, dest;\n\n    printf(&quot;Enter number of vertices: &quot;);\n    scanf(&quot;%d&quot;, &amp;vertices);\n    printf(&quot;Enter number of edges: &quot;);\n    scanf(&quot;%d&quot;, &amp;edges);\n\n    struct Graph* graph = createGraph(vertices);\n\n    printf(&quot;Enter edges (src dest): \\n&quot;);\n    for (int i = 0; i &lt; edges; i++) {\n        scanf(&quot;%d %d&quot;, &amp;src, &amp;dest);\n        addEdge(graph, src, dest);\n    }\n\n    findConnectedComponents(graph);\n\n    \/\/ Free allocated memory\n    for (int i = 0; i &lt; vertices; i++) {\n        struct Node* temp = graph-&gt;adjLists&#x5B;i];\n        while (temp) {\n            struct Node* toFree = temp;\n            temp = temp-&gt;next;\n            free(toFree);\n        }\n    }\n    free(graph-&gt;adjLists);\n    free(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 Structure<\/strong>: We define a <code>Graph<\/code> structure that contains the number of vertices and an array of adjacency lists.<\/li>\n\n\n\n<li><strong>Creating the Graph<\/strong>: The <code>createGraph<\/code> function initializes the graph.<\/li>\n\n\n\n<li><strong>Adding Edges<\/strong>: The <code>addEdge<\/code> function adds edges in both directions since the graph is undirected.<\/li>\n\n\n\n<li><strong>DFS Implementation<\/strong>: The <code>DFS<\/code> function traverses the graph and marks vertices as visited while printing them.<\/li>\n\n\n\n<li><strong>Finding Connected Components<\/strong>: The <code>findConnectedComponents<\/code> function loops through all vertices. If a vertex isn&#8217;t visited, it calls <code>DFS<\/code> to explore and print the component.<\/li>\n\n\n\n<li><strong>Memory Management<\/strong>: After processing, we free the allocated memory to avoid leaks.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Sample Input and Output<\/h3>\n\n\n\n<p>Assuming the input is as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>Enter number of vertices: 5<br>Enter number of edges: 4<br>Enter edges (src dest): <br>0 1<br>0 2<br>3 4<br><\/code><\/pre>\n\n\n\n<p>The output will be:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>Connected components:<br>Component: 0 2 1 <br>Component: 3 4 <br><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>This program successfully finds and displays connected components in a graph using depth-first search. It can be adapted to different graph sizes and structures by changing the input. If you have any questions or need further modifications, feel free to ask!<\/p>\n\n\n\n<p><\/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>Understanding Connected Components In graph theory, a connected component is a subset of vertices such that there is a path between any two vertices in this subset. In simpler terms, it means that you can travel between any two nodes in that subset without leaving it. Approach Implementation Steps C Code Explanation of the Code [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":610,"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-607","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\/607","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=607"}],"version-history":[{"count":4,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/607\/revisions"}],"predecessor-version":[{"id":1459,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/607\/revisions\/1459"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/610"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=607"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=607"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=607"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}