Friday, October 13, 2017

Program to Implement Breadth First Search Using Adjacency Matrix in C

/*==========================================================================================
 **
 **  File Name     : bfs1.c
 **  Creation Date : Sat 14 Oct 2017 12:17:50 AM IST
 **  Last Modified : Sat 14 Oct 2017 01:42:00 AM IST
 **  Compiler      : gcc
 **  Author        : Manoj Kumar Patra, Asst. Professor
 **  Organization  : Vignan University, Guntur, India.
 **
 **=========================================================================================*/

#include<stdio.h>
#include<stdlib.h>
#define MAX 100
int n;/*Number of vertices in the graph*/
int adj[MAX][MAX]; /*Adjacency Matrix*/
int visited[MAX]; /* Not Visited: 0 ,visited: 1 */
void create_graph();
void BFS_Traversal();
int queue[MAX], front=-1,rear=-1;
int isEmptyQueue();
void enQueue(int vertex);
int deQueue();
int main()
{
    printf("\n= = = = = = = = Depth First Search Using Adjacency Matrix = = = = = = = =\n");
    int s,i;
    printf("\nEnter Number of Vertices: ");
    scanf("%d",&n);
    printf("Enter the data into matrix:\n");
    create_graph();
    for(i=0; i<n; i++)
    {
        visited[i]=0;
    }
    printf("\nEnter starting vertex for Breadth First Search: ");
    scanf("%d", &s);
    printf("\nVisit Sequence: \n");
    BFS_Traversal(s);
    printf("\n\n");
}

void create_graph()
{
    int i,j;
    for(i=0; i<n; i++)
    {
        for(j=0; j<n; j++)
        {
            scanf("%d",&adj[i][j]);
        }
        printf("\n");
    }
    printf("\nThe adjecency matrix of the graph is:\n");
    printf("= = = = = = = = = = = = = = = = = = = = = = = = = = = = =\n");
    for(i=0;i<n;i++)
    {
        printf("\n");
        for(j=0;j<n;j++)
        {
            printf("%d\t",adj[i][j]);
        }
        printf("\n");
    }
    printf("= = = = = = = = = = = = = = = = = = = = = = = = = = = = =\n");
}

void BFS_Traversal(int i)
{
    int j;
    printf("V%d\t",i);
    if(front==-1)
    {
        visited[i]=1;
        enQueue(i);
    }
    for(j=0; j<n; j++)
    {
        if(visited[j]==0 && adj[i][j]==1)
        {
            visited[j]=1;
            enQueue(j);
        }
    }
    deQueue();
    if(!isEmptyQueue())
    {
        BFS_Traversal(queue[front]);
    }
}

int isEmptyQueue()
{
    if(front == -1 || front > rear )
        return 1;
    else
        return 0;
}

void enQueue(int vertex)
{
    if (front == -1)  /*If queue is initially empty */
    {
        front = 0;
    }
    rear = rear+1;
    queue[rear] = vertex ;
}

int deQueue()
{
    front = front+1;
}

No comments:

Post a Comment