#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
}*front=NULL,*rear=NULL;
void enqu(int x)
{
struct node *t;
t=(struct node*)malloc(sizeof(struct node));
if(t==NULL)
printf("queue is full");
else
{
t->data=x;
t->next=NULL;
if(front==NULL)
front=rear=t;
else
{
rear->next=t;
rear=t;
}
}
}
int deque()
{
int x=-1;
struct node *t;
if(front==NULL)
printf("queue i empty");
else
{
t=front;
x=t->data;
front=front->next;
free(t);
}
return x;
}
int qempty()
{
return front==NULL;
}
void bfs(int g[][7],int i,int n)
{
int v[7]={0};
v[i]=1;
printf("%d",i);
enqu(i);
while(!qempty())
{
int x=deque();
for(int j=1;j<n;j++)
{
if(g[x][j]==1 &&v[j]==0)
{
printf("%d ",j);
v[j]=1;
enqu(j);
}
}
}
}
void dfs(int g[][7],int i,int n)
{
static int v[7]={0};
printf("%d ",i);
v[i]=1;
for(int j=1;j<n;j++)
{
if(g[i][j]==1 && v[j]==0)
dfs(g,j,n);
}
}
int main()
{
int g[7][7]={{0,0,0,0,0,0,0},
{0,0,1,1,0,0,0},
{0,1,0,0,1,0,0},
{0,1,0,0,1,0,0},
{0,0,1,1,0,1,1},
{0,0,0,0,1,0,0},
{0,0,0,0,1,0,0}};
dfs(g,1,7);
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter