You are on page 1of 8

Graph:

Algorithm to find cycle of a Graph

Step 1: start
Step 2: initialize variable N
Step 3: Declare graph and cycle to nth.
Step 4: Define edges.
Step 5: Declare DFS function for cycle finding
Step 6: Check if vertex is already visited ignore
Step 7: If vertex is not visited then backtrack based on parents
to find the complete cycle.
Step 8: Declare function to print cycle
Step 9: stop

ALGORITHM
Step 1: call DFS traversal for the graph which can color the
vertices.
Step 2: If a partially visited vertex is found, backtrack till the
vertex is
reached again and mark all vertices in the path with a counter
which is cycle number.
Step 3: After completion of traversal, iterate for cyclic edge and
push them
into a separate adjacency list.
Step 4: Print the cycles number wise from the adjacency list

Code that find out the cycle of a graph:


#include <bits/stdc++.h>

using namespace std;

const int N = 100000;

vector<int> graph[N];

vector<int> cycles[N];

void dfs_cycle(int u, int p, int color[],


int mark[], int par[], int& cyclenumber)

if (color[u] == 2) {

return;

if (color[u] == 1) {

cyclenumber++;

int cur = p;

mark[cur] = cyclenumber;

while (cur != u) {

cur = par[cur];

mark[cur] = cyclenumber;

return;

par[u] = p;

color[u] = 1;

for (int v : graph[u]) {

if (v == par[u]) {
continue;

dfs_cycle(v, u, color, mark, par, cyclenumber);

color[u] = 2;

void addEdge(int u, int v)

graph[u].push_back(v);

graph[v].push_back(u);

void printCycles(int edges, int mark[], int& cyclenumber)

for (int i = 1; i <= edges; i++) {

if (mark[i] != 0)

cycles[mark[i]].push_back(i);

for (int i = 1; i <= cyclenumber; i++) {


// Print the i-th cycle

cout << "Cycle Number " << i << ": ";

for (int x : cycles[i])

switch(x)

case 1:

cout<<'a';

break;

case 2:

cout<<'b';

break;

case 3:

cout<<'c';

break;

case 4:

cout<<'d';

break;

case 5:

cout<<'e';

break;
case 6:

cout<<'f';

break;

case 7:

cout<<'g';

break;

case 8:

cout<<'h';

break;

case 9:

cout<<'i';

break;

case 10:

cout<<'j';

break;

case 11:

cout<<'k';

break;

case 12:

cout<<'l';
break;

case 13:

cout<<'m';

break;

cout << endl;

int main()

addEdge(1, 2);

addEdge(2, 3);

addEdge(3, 4);

addEdge(4, 6);

addEdge(4, 7);

addEdge(5, 6);

addEdge(3, 5);

addEdge(7, 8);
addEdge(6, 10);

addEdge(5, 9);

addEdge(10, 11);

addEdge(11, 12);

addEdge(11, 13);

addEdge(12, 13);

int color[N];

int par[N];

int mark[N];

int cyclenumber = 0;

int edges = 13;

dfs_cycle(1, 0, color, mark, par, cyclenumber);

printCycles(edges, mark, cyclenumber);

You might also like