C++ Program and Algorithm To Print All The Cycles
C++ Program and Algorithm To Print All The Cycles
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
vector<int> graph[N];
vector<int> cycles[N];
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;
if (v == par[u]) {
continue;
color[u] = 2;
graph[u].push_back(v);
graph[v].push_back(u);
if (mark[i] != 0)
cycles[mark[i]].push_back(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;
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;