Breadth First Search code with output


Code

#include<stdio.h>

#define SIZE 10

int vis[10];

typedef struct 
{
    int n;
    int adj_mat[15][15];
}graph; 

graph g;

typedef struct
{
    int front,rear,arr[SIZE];
}queue;

queue q;

void init()
{
    q.front=q.rear=-1;
}

int isEmpty()
{
    if(q.front==-1)
        return 1;
    return 0;
}

int isFull()
{
    if(q.rear==(SIZE-1))
        return 1;
    return 0;
}

void enqueue(int element)
{
        if(isFull())
        {
            printf("\nQueue overflow");
            return;
        }

        if(isEmpty())
            q.front++;
        q.arr[++q.rear] = element;
}

int dequeue()
{
    int element = q.arr[q.front];

    if(isEmpty())
    {
        printf("\nQueue underflow");
        return -1;
    }
    else 
    {
        if(q.front == q.rear)
            init();
        else
            q.front++;

        return element;
    }
}

void read_graph();
void bfs();

int main()
{
    int source;

    read_graph();

    printf("\nEnter source vertex ");
    scanf("%d",&source);

    printf("\nBFS = ");

    bfs(source);

    return 0;
}

void read_graph()
{
    int i,j;

    printf("Enter the no of vertices in the graph ");
    scanf("%d",&g.n);

    printf("\nEnter adjacency matrix\n");

    for(i=1;i<=g.n;i++)
    {
        for(j=1;j<=g.n;j++)
            scanf("%d",&g.adj_mat[i][j]);

        vis[i] = 0;
    }
}

void bfs(int source)
{
    int curr,i = 1;
    vis[source] = 1;

    init();

    enqueue(source);

    while(!isEmpty())
    {
        curr = dequeue();
        printf("%d ",curr);
        i = 1;

        while(i<=g.n)
        {
            if(vis[i]==0 && g.adj_mat[curr][i]==1)
            {
                vis[i] = 1;
                enqueue(i);
            }

            i++;
        }
    }
}



O/P


Breadth-First-Search-output

No comments:

Post a Comment