Pages

BFS and DFS on a graph represented using adjacency list C program

Saturday, 1 March 2014

#include<conio.h>#include<stdio.h>#include<stdlib.h>#define MAX 20typedefstructQ{intdata[MAX];intR,F;}Q;typedefstructnode{structnode*next;intvertex;}node;voidenqueue(Q*,int);intdequque(Q*);intempty(Q*);intfull(Q*);voidBFS(int);voidreadgraph();//create an adjecency listvoidinsert(intvi,intvj);//insert an edge (vi,vj)in adj.listvoidDFS(inti);intvisited[MAX];node*G[20];//heads of the linked listintn;// no of nodesvoidmain(){inti,op;clrscr();do{printf("\n\n1)Create\n2)BFS\n3)DFS\n4)Quit");printf("\nEnter Your Choice: ");scanf("%d",&op);switch(op){case1: readgraph();break;case2: printf("\nStarting Node No. : ");scanf("%d",&i);BFS(i);break;case3: for(i=0;i<n;i++)visited[i]=0;printf("\nStarting Node No. : ");scanf("%d",&i);DFS(i);break;}}while(op!=4);}voidBFS(intv){intw,i,visited[MAX];Qq;node*p;q.R=q.F=-1;//initialisefor(i=0;i<n;i++)visited[i]=0;enqueue(&q,v);printf("\nVisit\t%d",v);visited[v]=1;while(!empty(&q)){v=dequeue(&q);//insert all unvisited,adjacent vertices of v into queuefor(p=G[v];p!=NULL;p=p->next){w=p->vertex;if(visited[w]==0){enqueue(&q,w);visited[w]=1;printf("\nvisit\t%d",w);}}}}voidDFS(inti){node*p;printf("\n%d",i);p=G[i];visited[i]=1;while(p!=NULL){i=p->vertex;if(!visited[i])DFS(i);p=p->next;}}intempty(Q*P){if(P->R==-1)return(1);return(0);}intfull(Q*P){if(P->R==MAX-1)return(1);return(0);}voidenqueue(Q*P,intx){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;}}intdequeue(Q*P){intx;x=P->data[P->F];if(P->R==P->F){P->R=-1;P->F=-1;}elseP->F=P->F+1;return(x);}voidreadgraph(){inti,vi,vj,no_of_edges;printf("\nEnter no. of vertices :");scanf("%d",&n);//initialise G[] with NULLfor(i=0;i<n;i++)G[i]=NULL;//read edges and insert them in G[]printf("\nEnter no of edges :");scanf("%d",&no_of_edges);for(i=0;i<no_of_edges;i++){printf("\nEnter an edge (u,v) :");scanf("%d%d",&vi,&vj);insert(vi,vj);insert(vj,vi);}}voidinsert(intvi,intvj){node*p,*q;//acquire memory for the new nodeq=(node*)malloc(sizeof(node));q->vertex=vj;q->next=NULL;//insert the node in the linked list for the vertex no. viif(G[vi]==NULL)G[vi]=q;else{// go to the end of linked listp=G[vi];while(p->next!=NULL)p=p->next;p->next=q;}}