{"id":742,"date":"2024-10-14T14:15:01","date_gmt":"2024-10-14T08:45:01","guid":{"rendered":"https:\/\/codexplained.in\/?p=742"},"modified":"2025-11-24T15:48:02","modified_gmt":"2025-11-24T10:18:02","slug":"detection-of-cycle-in-graph","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=742","title":{"rendered":"Detection of Cycle in Graph"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Understanding Cycle Detection<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>In Undirected Graphs<\/strong>: A cycle exists if we can return to a previously visited vertex without using the same edge.<\/li>\n\n\n\n<li><strong>In Directed Graphs<\/strong>: A cycle exists if we can return to a previously visited vertex by following the directed edges.<\/li>\n<\/ol>\n\n\n\n<p>For this example, we will focus on detecting cycles in an <strong>undirected graph<\/strong> using Depth First Search (DFS).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">DFS Approach for Cycle Detection<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Start from any unvisited node and perform DFS.<\/li>\n\n\n\n<li>Keep track of visited nodes.<\/li>\n\n\n\n<li>If you encounter a node that has already been visited and is not the parent of the current node, then a cycle exists.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">C Program to Detect Cycle in an Undirected Graph<\/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    \/\/ Add edge from dest to src (undirected graph)\n    newNode = createNode(src);\n    newNode-&gt;next = graph-&gt;adjList&#x5B;dest];\n    graph-&gt;adjList&#x5B;dest] = newNode;\n}\n\n\/\/ DFS function to detect a cycle\nint isCyclicUtil(struct Graph* graph, int vertex, int visited&#x5B;], int parent) {\n    visited&#x5B;vertex] = 1; \/\/ Mark the current node as visited\n\n    struct Node* temp = graph-&gt;adjList&#x5B;vertex];\n    while (temp) {\n        int adjVertex = temp-&gt;vertex;\n\n        \/\/ If the adjacent vertex is not visited, recurse on it\n        if (!visited&#x5B;adjVertex]) {\n            if (isCyclicUtil(graph, adjVertex, visited, vertex)) {\n                return 1; \/\/ Cycle detected\n            }\n        }\n        \/\/ If the adjacent vertex is visited and is not the parent, a cycle exists\n        else if (adjVertex != parent) {\n            return 1; \/\/ Cycle detected\n        }\n        temp = temp-&gt;next; \/\/ Move to the next adjacent vertex\n    }\n    return 0; \/\/ No cycle found\n}\n\n\/\/ Function to detect cycle in the graph\nint isCyclic(struct Graph* graph) {\n    int visited&#x5B;MAX] = {0}; \/\/ Array to track visited nodes\n\n    \/\/ Call the utility function for each component\n    for (int i = 0; i &lt; graph-&gt;numVertices; i++) {\n        if (!visited&#x5B;i]) {\n            if (isCyclicUtil(graph, i, visited, -1)) {\n                return 1; \/\/ Cycle found\n            }\n        }\n    }\n    return 0; \/\/ No cycle found\n}\n\n\/\/ Main function\nint main() {\n    struct Graph* graph = createGraph(5); \/\/ Create a graph with 5 vertices\n\n    \/\/ Adding edges\n    addEdge(graph, 0, 1);\n    addEdge(graph, 1, 2);\n    addEdge(graph, 2, 0); \/\/ This creates a cycle\n    addEdge(graph, 1, 3);\n    addEdge(graph, 3, 4);\n\n    \/\/ Check for cycles\n    if (isCyclic(graph)) {\n        printf(&quot;Cycle detected in the graph.\\n&quot;);\n    } else {\n        printf(&quot;No cycle detected in the graph.\\n&quot;);\n    }\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>We represent the graph using an adjacency list where each vertex points to a list of its neighbors. Each node in the adjacency list is defined by 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 the specified number of vertices.<\/li>\n\n\n\n<li><strong>addEdge<\/strong>: Adds an edge between two vertices, ensuring the graph remains undirected by adding edges in both directions.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Cycle Detection Using DFS<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The <code>isCyclicUtil<\/code> function performs a DFS on the graph.<\/li>\n\n\n\n<li>It checks if the current node has been visited and whether it is the parent of the adjacent node. If it is visited and not the parent, a cycle is detected.<\/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 and add edges. We also check for cycles 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<ul class=\"wp-block-list\">\n<li>The edges added to the graph are:<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\">The edges added to the graph are:<br>0 \u2192 1<br>1 \u2192 2<br>2 \u2192 0 (creates a cycle)<br>1 \u2192 3<br>3 \u2192 4<\/pre>\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\">sqlCopy code<code>Cycle detected in the graph.\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>This program effectively detects cycles in an undirected graph using DFS. You can modify the edges to test different graphs. The approach is efficient and straightforward, making it suitable for intermediate-level understanding of graph algorithms.<\/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 Cycle Detection For this example, we will focus on detecting cycles in an undirected graph using Depth First Search (DFS). DFS Approach for Cycle Detection C Program to Detect Cycle in an Undirected Graph Explanation of the Code Input and Output Input (Edges of the graph): The edges added to the graph are:0 \u2192 [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":752,"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-742","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\/742","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=742"}],"version-history":[{"count":4,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/742\/revisions"}],"predecessor-version":[{"id":1432,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/742\/revisions\/1432"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/752"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=742"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=742"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=742"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}