0% found this document useful (0 votes)
10 views

Graph Program

The document contains C code to implement breadth-first search (BFS) on a graph represented using an adjacency matrix. It includes functions to create the graph by taking input from the user, perform BFS to find all nodes reachable from a given starting node, and a main function with a menu to call the other functions.

Uploaded by

faizasiddique262
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Graph Program

The document contains C code to implement breadth-first search (BFS) on a graph represented using an adjacency matrix. It includes functions to create the graph by taking input from the user, perform BFS to find all nodes reachable from a given starting node, and a main function with a menu to call the other functions.

Uploaded by

faizasiddique262
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 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