The Wayback Machine - https://web.archive.org/web/20241117110226/https://www.geeksforgeeks.org/cycles-of-length-n-in-an-undirected-and-connected-graph/
Open In App

Cycles of length n in an undirected and connected graph

Last Updated : 13 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an undirected and connected graph and a number n, count the total number of simple cycles of length n in the graph. A simple cycle of length n is defined as a cycle that contains exactly n vertices and n edges. Note that for an undirected graph, each cycle should only be counted once, regardless of starting vertex or direction.

Example : 

Input :  n = 4

Output : Total cycles = 3
Explanation : Following 3 unique cycles
0 -> 1 -> 2 -> 3 -> 0
0 -> 1 -> 4 -> 3 -> 0
1 -> 2 -> 3 -> 4 -> 1
Note* : There are more cycles but
these 3 are unique as 0 -> 3 -> 2 -> 1
-> 0 and 0 -> 1 -> 2 -> 3 -> 0 are
same cycles and hence will be counted as 1.

To solve this Problem, DFS(Depth First Search) can be effectively used. Using DFS we find every possible path of length (n-1) for a particular source (or starting point). Then we check if this path ends with the vertex it started with, if yes then we count this as the cycle of length n. Notice that we looked for path of length (n-1) because the nth edge will be the closing edge of cycle.

Every possible path of length (n-1) can be searched using only V – (n – 1) vertices (where V is the total number of vertices). 
For above example, all the cycles of length 4 can be searched using only 5-(4-1) = 2 vertices. The reason behind this is quite simple, because we search for all possible path of length (n-1) = 3 using these 2 vertices which include the remaining 3 vertices. So, these 2 vertices cover the cycles of remaining 3 vertices as well, and using only 3 vertices we can’t form a cycle of length 4 anyways. 

One more thing to notice is that, every vertex finds 2 duplicate cycles for every cycle that it forms. For above example 0th vertex finds two duplicate cycle namely 0 -> 3 -> 2 -> 1 -> 0 and 0 -> 1 -> 2 -> 3 -> 0. Hence the total count must be divided by 2 because every cycle is counted twice.

Implementation:

C++
// CPP Program to count cycles of length n
// in a given graph.
#include <bits/stdc++.h>
using namespace std;

// Number of vertices
const int V = 5;

void DFS(bool graph[][V], bool marked[], int n, int vert,
         int start, int& count)
{
    // mark the vertex vert as visited
    marked[vert] = true;

    // if the path of length (n-1) is found
    if (n == 0) {

        // mark vert as un-visited to make
        // it usable again.
        marked[vert] = false;

        // Check if vertex vert can end with
        // vertex start
        if (graph[vert][start] && graph[start][vert]) {
            count++;
            return;
        }
        else
            return;
    }

    // For searching every possible path of
    // length (n-1)
    for (int i = 0; i < V; i++)
        if (!marked[i] && graph[vert][i])

            // DFS for searching path by decreasing
            // length by 1
            DFS(graph, marked, n - 1, i, start, count);

    // marking vert as unvisited to make it
    // usable again.
    marked[vert] = false;
}

// Counts cycles of length N in an undirected
// and connected graph.
int countCycles(bool graph[][V], int n)
{
    // all vertex are marked un-visited initially.
    bool marked[V];
    memset(marked, 0, sizeof(marked));

    // Searching for cycle by using v-n+1 vertices
    int count = 0;
    for (int i = 0; i < V - (n - 1); i++) {
        DFS(graph, marked, n - 1, i, i, count);

        // ith vertex is marked as visited and
        // will not be visited again.
        marked[i] = true;
    }

    return count / 2;
}

int main()
{
    bool graph[][V] = { { 0, 1, 0, 1, 0 },
                        { 1, 0, 1, 0, 1 },
                        { 0, 1, 0, 1, 0 },
                        { 1, 0, 1, 0, 1 },
                        { 0, 1, 0, 1, 0 } };
    int n = 4;
    cout << "Total cycles of length " << n << " are "
         << countCycles(graph, n);
    return 0;
}
Java
// Java program to calculate cycles of
// length n in a given graph
public class Main {
    
    // Number of vertices
    public static final int V = 5;
    static int count = 0;
    
    static void DFS(int graph[][], boolean marked[],
                    int n, int vert, int start) {
        
        // mark the vertex vert as visited
        marked[vert] = true;
        
        // if the path of length (n-1) is found
        if (n == 0) {
            
            // mark vert as un-visited to 
            // make it usable again
            marked[vert] = false;
            
            // Check if vertex vert end 
            // with vertex start
            if (graph[vert][start] == 1) {
                count++;
                return;
            } else
                return;
        }
        
        // For searching every possible 
        // path of length (n-1)
        for (int i = 0; i < V; i++)
            if (!marked[i] && graph[vert][i] == 1)
            
                // DFS for searching path by
                // decreasing length by 1
                DFS(graph, marked, n-1, i, start);
        
        // marking vert as unvisited to make it
        // usable again
        marked[vert] = false;
    }
    
    // Count cycles of length N in an 
    // undirected and connected graph.
    static int countCycles(int graph[][], int n) {
        
        // all vertex are marked un-visited
        // initially.
        boolean marked[] = new boolean[V];
        
        // Searching for cycle by using 
        // v-n+1 vertices
        for (int i = 0; i < V - (n - 1); i++) {
            DFS(graph, marked, n-1, i, i);
            
            // ith vertex is marked as visited
            // and will not be visited again
            marked[i] = true;
        }
        
        return count / 2; 
    }
    
    // driver code
    public static void main(String[] args) {
        int graph[][] = {{0, 1, 0, 1, 0},
                        {1, 0, 1, 0, 1},
                        {0, 1, 0, 1, 0},
                        {1, 0, 1, 0, 1},
                        {0, 1, 0, 1, 0}};
        
        int n = 4;
        
        System.out.println("Total cycles of length "+
                          n + " are "+ 
                          countCycles(graph, n));
    }
}

// This code is contributed by nuclode
Python3
# Python Program to count
# cycles of length n
# in a given graph.
 
# Number of vertices
V = 5

def DFS(graph, marked, n, vert, start, count):

    # mark the vertex vert as visited
    marked[vert] = True
 
    # if the path of length (n-1) is found
    if n == 0: 

        # mark vert as un-visited to make
        # it usable again.
        marked[vert] = False
 
        # Check if vertex vert can end with
        # vertex start
        if graph[vert][start] == 1:
            count = count + 1
            return count
        else:
            return count
 
    # For searching every possible path of
    # length (n-1)
    for i in range(V):
        if marked[i] == False and graph[vert][i] == 1:

            # DFS for searching path by decreasing
            # length by 1
            count = DFS(graph, marked, n-1, i, start, count)
 
    # marking vert as unvisited to make it
    # usable again.
    marked[vert] = False
    return count
 
# Counts cycles of length
# N in an undirected
# and connected graph.
def countCycles( graph, n):

    # all vertex are marked un-visited initially.
    marked = [False] * V 
 
    # Searching for cycle by using v-n+1 vertices
    count = 0
    for i in range(V-(n-1)):
        count = DFS(graph, marked, n-1, i, i, count)
 
        # ith vertex is marked as visited and
        # will not be visited again.
        marked[i] = True
    
    return int(count/2)
 
# main :
graph = [[0, 1, 0, 1, 0],
         [1 ,0 ,1 ,0, 1],
         [0, 1, 0, 1, 0],
         [1, 0, 1, 0, 1],
         [0, 1, 0, 1, 0]]
          
n = 4
print("Total cycles of length ",n," are ",countCycles(graph, n))

# this code is contributed by Shivani Ghughtyal
C#
// C# program to calculate cycles of
// length n in a given graph
using System;

class GFG 
{
    
    // Number of vertices
    public static int V = 5;
    static int count = 0;
    
    static void DFS(int [,]graph, bool []marked,
                    int n, int vert, int start) 
    {
        
        // mark the vertex vert as visited
        marked[vert] = true;
        
        // if the path of length (n-1) is found
        if (n == 0) 
        {
            
            // mark vert as un-visited to 
            // make it usable again
            marked[vert] = false;
            
            // Check if vertex vert end 
            // with vertex start
            if (graph[vert, start] == 1)
            {
                count++;
                return;
            } 
            else
                return;
        }
        
        // For searching every possible 
        // path of length (n-1)
        for (int i = 0; i < V; i++)
            if (!marked[i] && graph[vert, i] == 1)
            
                // DFS for searching path by
                // decreasing length by 1
                DFS(graph, marked, n - 1, i, start);
        
        // marking vert as unvisited to make it
        // usable again
        marked[vert] = false;
    }
    
    // Count cycles of length N in an 
    // undirected and connected graph.
    static int countCycles(int [,]graph, int n) 
    {
        
        // all vertex are marked un-visited
        // initially.
        bool []marked = new bool[V];
        
        // Searching for cycle by using 
        // v-n+1 vertices
        for (int i = 0; i < V - (n - 1); i++) 
        {
            DFS(graph, marked, n - 1, i, i);
            
            // ith vertex is marked as visited
            // and will not be visited again
            marked[i] = true;
        }
        
        return count / 2; 
    }
    
    // Driver code
    public static void Main()
    {
        int [,]graph = {{0, 1, 0, 1, 0},
                        {1, 0, 1, 0, 1},
                        {0, 1, 0, 1, 0},
                        {1, 0, 1, 0, 1},
                        {0, 1, 0, 1, 0}};
        
        int n = 4;
        
        Console.WriteLine("Total cycles of length "+
                        n + " are "+ 
                        countCycles(graph, n));
    }
}

/* This code contributed by PrinciRaj1992 */
JavaScript
<script>

// JavaScript program to calculate cycles of
// length n in a given graph

// Number of vertices
var V = 5;
var count = 0;

function DFS(graph, marked, n, vert, start) 
{
    
    // mark the vertex vert as visited
    marked[vert] = true;
    
    // if the path of length (n-1) is found
    if (n == 0) 
    {
        
        // mark vert as un-visited to 
        // make it usable again
        marked[vert] = false;
        
        // Check if vertex vert end 
        // with vertex start
        if (graph[vert][start] == 1)
        {
            count++;
            return;
        } 
        else
            return;
    }
    
    // For searching every possible 
    // path of length (n-1)
    for (var i = 0; i < V; i++)
        if (!marked[i] && graph[vert][i] == 1)
        
            // DFS for searching path by
            // decreasing length by 1
            DFS(graph, marked, n - 1, i, start);
    
    // marking vert as unvisited to make it
    // usable again
    marked[vert] = false;
}

// Count cycles of length N in an 
// undirected and connected graph.
function countCycles(graph, n) 
{
    
    // all vertex are marked un-visited
    // initially.
    var marked = Array(V).fill(false);
    
    // Searching for cycle by using 
    // v-n+1 vertices
    for (var i = 0; i < V - (n - 1); i++) 
    {
        DFS(graph, marked, n - 1, i, i);
        
        // ith vertex is marked as visited
        // and will not be visited again
        marked[i] = true;
    }
    
    return parseInt(count / 2); 
}

// Driver code
var graph = [[0, 1, 0, 1, 0],
                [1, 0, 1, 0, 1],
                [0, 1, 0, 1, 0],
                [1, 0, 1, 0, 1],
                [0, 1, 0, 1, 0]];

var n = 4;

document.write("Total cycles of length "+
                n + " are "+ 
                countCycles(graph, n));

</script> 

Output
Total cycles of length 4 are 3

Time Complexity: O(V*V)
Space Complexity: O(V)

 



Previous Article
Next Article

Similar Reads

Convert undirected connected graph to strongly connected directed graph
Given an undirected graph of N vertices and M edges, the task is to assign directions to the given M Edges such that the graph becomes Strongly Connected Components. If a graph cannot be converted into Strongly Connected Components then print "-1". Examples: Input: N = 5, Edges[][] = { { 0, 1 }, { 0, 2 }, { 1, 2 }, { 1, 4 }, { 2, 3 }, { 3, 4 } } Ou
14 min read
Print all the cycles in an undirected graph
Given an undirected graph, print all the vertices that form cycles in it. Pre-requisite: Detect Cycle in a directed graph using colors In the above diagram, the cycles have been marked with dark green color. The output for the above will be 1st cycle: 3 5 4 6 2nd cycle: 5 6 10 93rd cycle: 11 12 13 Approach: Using the graph coloring method, mark all
11 min read
Product of lengths of all cycles in an undirected graph
Given an undirected and unweighted graph. The task is to find the product of the lengths of all cycles formed in it.Example 1: The above graph has two cycles of length 4 and 3, the product of cycle lengths is 12. Example 2: The above graph has two cycles of length 4 and 3, the product of cycle lengths is 12. Approach: Using the graph coloring metho
12 min read
Print all Hamiltonian Cycles in an Undirected Graph
Given an undirected Graph consisting of N nodes in the form of an adjacency matrix graph[][] of size N*N, the task is to print all Hamiltonian cycles possible in the given undirected Graph (taking starting vertex as '0'). A Hamiltonian cycle (or Hamiltonian circuit) is a Hamiltonian Path such that there is an edge (in the graph) from the last verte
15 min read
Count of simple cycles in an undirected graph having N vertices
Given an undirected unweighted graph of N vertices in the form of adjacency matrix adj[][], the task is to find the number of simple cycles in it. Input: adj[][] = { { 0, 1, 1, 1 }, { 1, 0, 1, 0 }, { 1, 1, 0, 1 }, { 1, 0, 1, 0 } }Output: 2Explanation: The graph is shown below as: The given graph consists of two simple cycles as shownInput: adj[][]
12 min read
What is Undirected Graph? | Undirected Graph meaning
An undirected graph is a type of graph where the edges have no specified direction assigned to the them. Characteristics of an Undirected Graph:Edges in an undirected graph are bidirectional in nature.In an undirected graph, there is no concept of a "parent" or "child" vertex as there is no direction to the edges.An undirected graph may contain loo
2 min read
Queries to check if vertices X and Y are in the same Connected Component of an Undirected Graph
Given an undirected graph consisting of N vertices and M edges and queries Q[][] of the type {X, Y}, the task is to check if the vertices X and Y are in the same connected component of the Graph. Examples: Input: Q[][] = {{1, 5}, {3, 2}, {5, 2}} Graph: 1-3-4 2 | 5 Output: Yes No No Explanation: From the given graph, it can be observed that the vert
11 min read
Kth largest node among all directly connected nodes to the given node in an undirected graph
Given two arrays u and v, representing a graph such that there is an undirected edge from u[i] to v[i] (0 ? v[i], u[i] < N) and each node has some value val[i] (0 ? i < N). For each node, if the nodes connected directly to it are sorted in descending order according to their values (in case of equal values, sort it according to their indices
7 min read
Count of unique lengths of connected components for an undirected graph using STL
Given an undirected graph, the task is to find the size of each connected component and print the number of unique sizes of connected components As depicted above, the count(size of the connected component) associated with the connected components is 2, 3, and 2. Now, the unique count of the components is 2 and 3. Hence, the expected result is Coun
10 min read
Check if longest connected component forms a palindrome in undirected graph
Given an undirected graph with V vertices and E edges, the task is to check that if the largest connected component of the graph forms a palindrome in the undirected graph. Examples: Input: Output: Longest connected component is Palindrome Explanation: Longest connected component is {5, 15, 5} which forms an palindrome by values. Input: Output: Lon
15+ min read
Largest subarray sum of all connected components in undirected graph
Given an undirected graph with V vertices and E edges, the task is to find the maximum contiguous subarray sum among all the connected components of the graph. Examples: Input: E = 4, V = 7 Output: Maximum subarray sum among all connected components = 5 Explanation: Connected Components and maximum subarray sums are as follows: [3, 2]: Maximum suba
14 min read
Maximum GCD of all nodes in a connected component of an Undirected Graph
Given an undirected graph consisting of V vertices and a 2d array E[][2] denoting edges between pairs of nodes. Given another array arr[] representing values assigned to each node, the task is to find the maximum GCD among the GCD of all connected components in the graph. Examples: Input: V = 5, E[][2] = {{1, 3}, {2, 3}, {1, 2}}, arr[] = {23, 43, 1
10 min read
Connected Components in an Undirected Graph
Given an undirected graph, the task is to print all the connected components line by line. Examples: Input: Consider the following graph Output:0 1 23 4Explanation: There are 2 different connected components.They are {0, 1, 2} and {3, 4}. Recommended PracticeNumber of ProvincesTry It! We have discussed algorithms for finding strongly connected comp
14 min read
Maximum sum of values of nodes among all connected components of an undirected graph
Given an undirected graph with V vertices and E edges. Every node has been assigned a given value. The task is to find the connected chain with the maximum sum of values among all the connected components in the graph. Examples: Input: V = 7, E = 4 Values = {10, 25, 5, 15, 5, 20, 0}   Output : Max Sum value = 35 Explanation: Component {1, 2} - Valu
15+ min read
Sum of the minimum elements in all connected components of an undirected graph
Given an array A of N numbers where A i represent the value of the (i+1) th node. Also given are M pair of edges where u and v represent the nodes that are connected by an edge. The task is to find the sum of the minimum element in all the connected components of the given undirected graph. If a node has no connectivity to any other node, count it
7 min read
Convert the undirected graph into directed graph such that there is no path of length greater than 1
Given an undirected graph with N vertices and M edges and no self loops or multiple edges. The task is to convert the given undirected graph into a directed graph such that there is no path of length greater than 1. If it is possible to make such a graph then print two space-separated integers u and v in M lines where u, v denotes source and destin
10 min read
Connect a graph by M edges such that the graph does not contain any cycle and Bitwise AND of connected vertices is maximum
Given an array arr[] consisting of values of N vertices of an initially unconnected Graph and an integer M, the task is to connect some vertices of the graph with exactly M edges, forming only one connected component, such that no cycle can be formed and Bitwise AND of the connected vertices is maximum possible. Examples: Input: arr[] = {1, 2, 3, 4
9 min read
Program to find the diameter, cycles and edges of a Wheel Graph
Wheel Graph: A Wheel graph is a graph formed by connecting a single universal vertex to all vertices of a cycle. Properties: Wheel graphs are Planar graphs.There is always a Hamiltonian cycle in the Wheel graph.Chromatic Number is 3 and 4, if n is odd and even respectively. Problem Statement: Given the Number of Vertices in a Wheel Graph. The task
7 min read
Count of all cycles without any inner cycle in a given Graph
Given an undirected connected graph consisting of N vertices numbered [0, N-1] and E edges, the task is to count the number of cycles such that any subset of vertices of a cycle does not form another cycle.Examples: Input: N = 2, E = 2, edges = [{0, 1}, {1, 0}] Output: 1 Explanation: Only one cycle exists between the two vertices. Input: N = 6, E =
5 min read
Check if a cycle exists between nodes S and T in an Undirected Graph with only S and T repeating
Given an undirected graph with N nodes and two vertices S & T, the task is to check if a cycle between these two vertices exists or not, such that no other node except S and T appear more than once in that cycle. Print Yes if it exists otherwise print No. Example: Input: N = 7, edges[][] = {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 2}, {2, 6}
10 min read
Check if a cycle exists between nodes S and T in an Undirected Graph with only S and T repeating | Set - 2
Given an undirected graph with N nodes and two vertices S & T, the task is to check if a cycle between these two vertices exists (and return it) or not, such that no other node except S and T appears more than once in that cycle. Examples: Input: N = 7, edges[][] = {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 2}, {2, 6}, {6, 0}}, S = 0, T = 4 O
12 min read
Peterson's Algorithm for Mutual Exclusion | Set 2 (CPU Cycles and Memory Fence)
Problem: Given 2 process i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support. We strongly recommend to refer below basic solution discussed in previous article. Peterson's Algorithm for Mutual Exclusion | Set 1We would be resolving 2 issues in the previous algorithm.  Wast
11 min read
Print all shortest paths between given source and destination in an undirected graph
Given an undirected and unweighted graph and two nodes as source and destination, the task is to print all the paths of the shortest length between the given source and destination.Examples: Input: source = 0, destination = 5 Output: 0 -> 1 -> 3 -> 50 -> 2 -> 3 -> 50 -> 1 -> 4 -> 5 Explanation: All the above paths are of
13 min read
Building an undirected graph and finding shortest path using Dictionaries in Python
Prerequisites: BFS for a GraphDictionaries in Python In this article, we will be looking at how to build an undirected graph and then find the shortest path between two nodes/vertex of that graph easily using dictionaries in Python Language. Building a Graph using Dictionaries Approach: The idea is to store the adjacency list into the dictionaries,
3 min read
Find the ratio between Duplets and Triplets in an undirected Graph
Given an undirected graph, with n nodes numbered from 0 to n-1. Given a 2D integer array of edges where edges[i]= [ai, bi] denotes that there exists an undirected edge between connected nodes ai and bi. The task is to find the ratio between Duplets and Triplets from the given graph where Duplet can be defined as a component with 2 nodes and a Tripl
11 min read
Minimum edges to be removed from given undirected graph to remove any existing path between nodes A and B
Given two integers N and M denoting the number of vertices and edges in the graph and array edges[][] of size M, denoting an edge between edges[i][0] and edges[i][1], the task is to find the minimum edges directly connected with node B that must be removed such that there exist no path between vertex A and B. Examples: Input: N = 4, A = 3, B = 2, e
9 min read
What is the difference between an undirected and a directed Graph?
Undirected and Directed graphs are fundamental concepts in graph theory, it is basically a branch of mathematics that deals with the study of graphs and it consists of a set of vertices(nodes) connected by edges. In this article, we will learn the differences between an undirected and a directed graph., Undirected Graphs An undirected graph is a gr
3 min read
Difference Between sum of degrees of odd and even degree nodes in an Undirected Graph
Given an undirected graph with N vertices and M edges, the task is to find the absolute difference Between the sum of degrees of odd degree nodes and even degree nodes in an undirected Graph. Examples: Input: N = 4, edges[][] = { { 1, 2 }, { 1, 3 }, { 1, 4 }, { 2, 3 }, { 2, 4 }, { 3, 4 } } Output: 12 Explanation: Below is the graph for the above in
7 min read
Eulerian path and circuit for undirected graph
Eulerian Path is a path in a graph that visits every edge exactly once. Eulerian Circuit is an Eulerian Path that starts and ends on the same vertex. How to find whether a given graph is Eulerian or not? The problem is same as following question. "Is it possible to draw a given graph without lifting pencil from the paper and without tracing any of
15+ min read
Undirected graph splitting and its application for number pairs
Graphs can be used for seemingly unconnected problems. Say the problem of cards which have numbers on both side and you try to create a continuous sequence of numbers using one side. This problem leads to problems in how to split a graph into connected subsets with cycles and connected subsets without cycles. There are known algorithms to detect if
15+ min read
Practice Tags :
three90RightbarBannerImg