Thursday 18 June 2015

C Program to check whether a graph contains a cycle or not









We will be using the following graph

As we know a graph may or may not contain a cycle i.e a graph which does not contain a cycle is called a tree. We can use either BFS (Breadth First Search) or Depth First Search (DFS) to check whether a graph contains a cycle or not .
So basically here we are carrying out the dfs of a graph and for each graph node we check if its adjaceny list contains a element or node that is already visited. A graph may have cycle if and only if if there exists a back link to node predecessor from its ancestors.
Here we will be using the same array visited as in DFS to keep track of the nodes that are visited.
Below is the C implementation of the same.

#include<stdio.h>
#include<stdlib.h>
int visited[10]={0,0,0,0};//take it to the no of nodes in graph ,or allocate memory dynamically
int flag=0;
struct node
{
    int a;
    struct node * next;
};
struct graph
{
    int v;
    struct node **array;
};
void addedge(struct graph *g,int s,int d)
{
    struct node*temp ;
    temp= (struct node *)malloc(sizeof(struct node));
    temp->a=d;
    temp->next=g->array[s];// adding the node at the starting of the list
    g->array[s]=temp;
}
void dfs(int x,struct graph *g)
{
struct node *temp;
if(visited[x]==1)
{
   flag=1;
   return;
}
else
   {
       printf("%d",x);
       visited[x]=1;

temp=g->array[x];
while(temp)
{
    dfs(temp->a,g);
    temp=temp->next;
}
   }
   return;
}

int main()
{
struct graph *g;
g=(struct graph *)malloc(sizeof(struct graph));
g->v=4;
g->array=(struct node **)malloc(5*sizeof(struct node*));
int i;
for(i=0;i<4;i++) //intializing the graph
{
    struct node *n;
    n= (struct node*)malloc(sizeof(struct node));
    n->a=i;
    n->next=NULL;
    g->array[i]=n;
}
addedge(g,0,1); //Creating the graph first here
addedge(g,0,2);
addedge(g,1,2);
addedge(g,2,3);
addedge(g,2,0);
addedge(g,3,3);
printf("DFs=\n");
dfs(2,g);
printf("\n");
if(flag)
printf("There exists a cycle");
else
printf("There does not exists a cycle");
return 0;
}

Output:





No comments:

Post a Comment