Wednesday 10 June 2015

Program for Breadth First Search traversal of a graph in C
The graph used is shown below:








As we know the bfs traverses the tree or a graph across the width or say breadth of the graph. The bfs traversal of the graph is very much similar to the bfs of a tree with a difference that unlike trees graphs may have cycle too and we may traverse back to the previous visited node once again in the traversal if the next node that has to be visited has a link to the previously visited nodes.

So, We will be using an array "visit" to store the status of each node whether visited or not.
We will start from node '0' and visits its adjacent nodes using its adjacency list and store all its adjacent nodes in the queue provided its is not already visited using "visit" array, initially the queue contains the starting node i.e. 0

After that we process each element of the queue until it is empty 
The implementation of the above concepts is shown below :

#include<stdio.h>
#include<stdlib.h>
int visited[10];//take it to the no of nodes in graph ,or allocate memory dynamically
struct node
{
    int a;
    struct node * next;
};
struct graph
{
    int v;
    struct node **array;
};
void addedge(struct graph *g,int s,int d)
{
    struct node*temp ;
    temp= (struct node *)malloc(sizeof(struct node));
    temp->a=d;
    temp->next=g->array[s];// adding the node at the starting of the list
    g->array[s]=temp;
}

void bfs(struct graph *g)
{
    int i=0,v,f=0,r=0,c;
    struct node *temp;
int array[10],visit[5]={1,0,0,0,0};//we can initialize with only 1 also the rest will get by default to '0'
array[0]=0;
for(i=f;i<=r;i++)
{
    v=array[i];
    printf("%d",v);
    printf(" ");
    temp=g->array[v];
    while(temp->a!=v)
    {
        c=temp->a;
          if(visit[c]==0)
          {
             array[++r]=temp->a;
             visit[c]=1;
          }
        temp=temp->next;
    }
}

}

int main()
{
struct graph *g;
g=(struct graph *)malloc(sizeof(struct graph));
g->v=5;
g->array=(struct node **)malloc(5*sizeof(struct node*));
int i;
for(i=0;i<5;i++) //intializing the graph
{
    struct node *n;
    n= (struct node*)malloc(sizeof(struct node));
    n->a=i;
    n->next=NULL;
    g->array[i]=n;
}
addedge(g,0,1); //Creating the graph first here 
addedge(g,0,4);
addedge(g,4,0);
addedge(g,4,1);
addedge(g,4,3);
addedge(g,3,4);
addedge(g,3,1);
addedge(g,3,2);
addedge(g,1,0);
addedge(g,1,2);
addedge(g,1,3);
addedge(g,1,4);
addedge(g,2,1);
addedge(g,2,3);
printf("BFS\n");
bfs(g);
return 0;

}
OUTPUT:


No comments:

Post a Comment