Write a Program to implement Breadth First Traversal Algorithm. - Data Structure using C

Translate

Friday, December 11, 2020

Write a Program to implement Breadth First Traversal Algorithm.

 Write a Program to implement Breadth First Traversal Algorithm

Sample input

case=1

input= 5

0 1 1 1 0

1 0 1 0 0 

1 1 0 0 1

1 0 0 0 0 

0 0 1 0 0

0

Sample output=0 1 2 3 4 

code👇👇👇👇👇👇👇👇👇

#include<stdio.h>


int a[20][20],q[20],visited[20],n,f=-1,r=-1;


void bfs(int v)

{

    int i;

    for(i=0;i<n;i++)

    {

        

        if(a[v][i]!=0 && visited[i]==0)

        {

            r=r+1;

            q[r]=i;

            visited[i]=1;

            printf("%d ",i);

        }

    }

    

    f=f+1;

    if(f<=r)

    {

        bfs(q[f]);

    }

}


int main()

{

    int v,i,j;

    printf("\nEnter the number of vertices: ");

    scanf("%d ",&n);

    

    for(i=0;i<n;i++)

    {

        visited[i]=0;

    }

    

    

    printf(" \nEnter the graph data in the matrix form :\n");

    

    for(i=0;i<n;i++)

    {

        for(j=0;j<n;j++)

        {

         

         scanf("%d",&a[i][j]);

         

        }

    }

    

    printf("\n Enter the starting vertex:\n");

    

    scanf("%d",&v);

    f=r=0;

    q[r]=v;

    printf("\n The BFS traversal is :\n");

    visited[v]=1;

    printf("%d   ",v);

    

    bfs(v);

    if(r!=n-1)

    {

        printf("\n BFS is not possible");

        

    }

}



No comments:

Post a Comment

Introduction to Arrays

  Introduction to Arrays An array is a data structure that allows you to store a collection of elements of the same type. Each element in th...