Open In App

Cycles of length n in an undirected and connected graph

Last Updated : 27 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an undirected and connected graph and a number n, count total number of cycles of length n in the graph. A cycle of length n simply means that the cycle contains n vertices and n edges. And we have to count all such cycles that exist. 

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 – (n1) 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
Maximum number of edges among all connected components of an undirected graph
Given integers 'N' and 'K' where, N is the number of vertices of an undirected graph and 'K' denotes the number of edges in the same graph (each edge is denoted by a pair of integers where i, j means that the vertex 'i' is directly connected to the vertex 'j' in the graph). The task is to find the maximum number of edges among all the connected com
6 min read
Clone an undirected graph with multiple connected components
Given an undirected graph with multiple connected components, the task is to clone the graph. Cloning a graph with a single connected component can be seen here. Examples: An example of an undirected graph with 3 connected components: Approach: The idea is to follow the same approach posted for cloning connected graph, but with every node so that w
15 min read
Program to count Number of connected components in an undirected graph
Given an undirected graph g, the task is to print the number of connected components in the graph. Examples: Input: Output: 3 There are three connected components: 1 - 5, 0 - 2 - 4 and 3 Approach: DFS visit all the connected vertices of the given vertex. When iterating over all vertices, whenever we see unvisited node, it is because it was not visi
6 min read
Practice Tags :