#include <stdio.h>
#include <stdlib.h>
typedef struct node{int key;struct node * next;}node;
node * init_node(node * n,int b){n=(node *)malloc(sizeof(node));n->key=b;n->next=NULL;return n;}
node **list,*front=NULL,*rear=NULL;
void enqueue(node * n)
{ if(rear==NULL)front=rear=n;
else{ rear->next=n;rear=n; } }
node * dequeue()
{
if(front==NULL&&rear==NULL){return NULL;}
if(front==rear){ node *temp=front;front=rear=NULL;return temp;}
node * temp=front;front=front->next;return temp;
}
void add_edge(int a,int b)
{ node * ptr=NULL,*n=NULL,*p;
n=init_node(n,b);
if(list[a]==NULL){p=init_node(p,a);list[a]=p;}
ptr=list[a]; while(ptr->next!=NULL)ptr=ptr->next;ptr->next=n;
ptr=NULL;n=NULL;
n=init_node(n,a);
if(list[b]==NULL){p=init_node(p,b);list[b]=p;}
ptr=list[b]; while(ptr->next!=NULL)ptr=ptr->next;ptr->next=n;
}
void dfs(int s,int n)
{ node * ptr;int visited[n],i,d=6,parent[n],distance[n],parenti;
for(i=0;i<n;i++){visited[i]=0;parent[i]=0;distance[i]=-1;}
if(list[s]==NULL)return;
enqueue(list[s]);
parenti=s;
distance[s]=0;
visited[s]=1;
printf("\nDFS Distance from %d :\n",s);
while(front!=NULL)
{
ptr=dequeue();
parenti=ptr->key;
ptr=list[ptr->key]->next;
while(ptr!=NULL)
{ if(!visited[ptr->key])
{enqueue(ptr);if(parent[ptr->key]==0)parent[ptr->key]=parenti;visited[ptr->key]=1;
distance[ptr->key] =distance[parent[ptr->key]]+6;
printf(" node-%d:parent-:%d:distance:%d\n ",ptr->key,parent[ptr->key],distance[ptr->key]);}
ptr=ptr->next;
}
}
}
int main()
{int n=10,i,j;node *ptr=NULL;
list=(node **)malloc(n*(sizeof(node *)));
for(i=0;i<n;i++)
{ list[i]=(node *)malloc(n*(sizeof(node *)));list[i]=NULL;}
add_edge(2,1);
add_edge(0,1);add_edge(2,0);
add_edge(2,3);
add_edge(9,6);add_edge(9,0);add_edge(9,5);add_edge(9,4);add_edge(9,7);add_edge(9,8);add_edge(9,3);
add_edge(8,7);add_edge(8,6);
add_edge(7,2);add_edge(7,2);
add_edge(6,0);add_edge(6,1);
add_edge(5,4);add_edge(5,2);add_edge(5,3);
add_edge(4,2);
add_edge(3,0);add_edge(3,1);
add_edge(1,0);
for(j=0;j<n;j++)
if(list[j]!=NULL)
{ ptr=list[j];
while(ptr!=NULL){printf("%d --> ",ptr->key);ptr=ptr->next;}
printf("\n");
}
dfs(3,10);
return 0;
}