Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

#include<stdio.

h>

int a[20][20],q[20],visited[20];

int n,i,j,f=0,r=-1;

void create_graph()

printf("enter the number of cities:");

scanf("%d",&n);

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

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

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

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

return;

void bfs(int v)

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

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

q[++r]=i;

if(f<=r)

visited[q[f]]=1;

bfs(q[f++]);

void main()

int v,choice;

while(1)

printf("\n 1:create a graph of n cities using adjacency matrix");


printf("\n 2:print all the nodes reachable from a given starting nodes in a graph using BFS");

printf("\n 3:exit");

printf("\n enter your choice:");

scanf("%d",&choice);

switch(choice)

case 1:create_graph();

break;

case 2:printf("enter the source vertex:");

scanf("%d",&v);

if((v<1)||(v>n))

printf("\nenter a valid source vertex");

else

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

visited[i]=0;

visited[v]=1;

bfs(v);

printf("the reachable node from node %d:\n",v);

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

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

printf("node %d\n",i);

break;

case 3:return;

default:printf("invalid choice");

You might also like