Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 130 additions & 0 deletions detect Cycle in Graph by BFS
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
-1--->if any vertex unvisited
0---->if any vertex visited and push into the stack
1---->if any vertex poped(means already complete don't considered)

if any vertex alreay adjacency visited and not poped means in 0 position then graph conation cycle



#include<stdio.h>
#include<stdlib.h>
#define v 5
int arr[v][v];
int visited[v];
int stack[v];
int top=-1;

void push(int data)
{
stack[++top]=data;
}

int pop()
{
return stack[top--];
}

int peek()
{
return stack[top];
}

void Dfs()
{
int i,x,y,flag=0;
while(top!=-1)
{
for(i=0;i<v;i++)
{
x=peek();
if(arr[x][i]==1)
{
if(visited[i]==-1)
{
push(i);
visited[i]=0;
i=-1;
}
else
{
if(visited[i]==0)
{
flag=1;
break;
}
}
}
}
if(flag==1)
{
printf("\nGraph conation cycle : %d---%d",x,i);
break;
}
else
{
y=pop();
visited[y]=1;

}
}
if(flag!=1)
printf("Graph contain no cycle ");
}

or
===

void Dfs()
{
int i,x,y,flag=0;
for(i=0;i<v;i++)
{
x=peek();
if(arr[x][i]==1)
{
if(visited[i]==-1)
{
push(i);
visited[i]=0;
i=-1;
}
else
{
if(visited[i]==0)
{
flag=1;
break;
}
}
}
}
if(flag==1)
printf("\nGraph conation cycle");
else
{
y=pop();
visited[y]=1;
if(top!=-1)
Dfs();
else
printf("\nGraph conation no cycle ") ;
}

}


void main()
{
int i,j,root;
printf("enter adjacency matrix : \n");
for(i=0;i<v;i++)
for(j=0;j<v;j++)
scanf("%d",&arr[i][j]);
for(i=0;i<v;i++)
visited[i]=-1;
printf("from Where you want to start: ");
scanf("%d",&root);
visited[root]=0;
push(root);
Dfs();
}