C source code for implementation of BFS and DFS
/* adjacency matrix */
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
typedef struct queue
{
int r,f;
int data[MAX];
}q;
void addqueue(q *p,int x);
int delqueue(q *p);
int empty(q *p);
void bfs(int);
void dfs(int);
int G[MAX][MAX];
int n=0;
int visited[MAX];
void main()
{
int i,j,v,op,m;
clrscr();
printf("\nenter the number of vertices");
scanf("%d",&n);
printf("\nenter the number of edges");
scanf("%d",&m);
for(i=0;i<n;i++)
for(j=0;j<m;j++)
G[i][j]=0;
printf("\nenter graph as a list of edges(starting vtex is 0)");
for(v=0;v<m;v++)
{
printf("\nenter the next edge(starting vtex,end vtex)");
scanf("%d%d",&i,&j);
G[i][j]=G[j][i]=1;
}
do
{
printf("\n1.dfs\n2.bfs\n3.display\n4.quit");
printf("\nenter your choice");
scanf("%d",&op);
switch(op)
{
case 1:
printf("\nenter the starting vertex for dfs");
scanf("%d",&v);
for(i=0;i<n;i++)
visited[i]=0;
dfs(v);
break;
case 2:
printf("\nenter the starting vertex for bfs");
scanf("%d",&v);
bfs(v);
break;
case 3:
printf("\nadjacency matrix is:");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d",G[i][j]);
}
break;
}
}while(op!=4);
}
void bfs(int v)
{
int i;
int visited[MAX];
q Q;
Q.r=Q.f=-1;
for(i=0;i<n;i++)
visited[i]=0;
addqueue(&Q,v);
printf("\nvisit %d",&v);
visited[v]=1;
while(!empty(&Q))
{
v=delqueue(&Q);
for(i=0;i<n;i++)
if(visited[i]==0&&G[v][i]!=0)
{
addqueue(&Q,i);
visited[i]=1;
printf("\n%d",i);
}
}
}
void dfs(int i)
{
int j;
printf("\n%d",i);
visited[i]=1;
for(j=0;j<n;j++)
if(!visited[j]&&G[i][j]==1)
dfs(j);
}
void addqueue(q *p,int x)
{
if(p->r==-1)
{
p->r=p->f=0;
p->data[p->r]=x;
}
else
{
p->r=p->r+1;
p->data[p->r]=x;
}
}
int delqueue(q *p)
{
int x;
x=p->data[p->f];
if(p->r==p->f)
{
p->r=-1;
p->f=-1;
}
else
p->f=p->f+1;
return(x);
}
int empty(q *p)
{
if(p->r==-1)
return(1);
return(0);
}
0 comments:
Post a Comment