Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
11 views3 pages

Program 11

The document outlines a C program for creating a graph of cities using an adjacency matrix and implementing a breadth-first search (BFS) to determine the reachability of nodes from a given source. It includes code for inputting the number of vertices, the adjacency matrix, and the source node, followed by the BFS algorithm to identify reachable nodes. Additionally, it provides examples of adjacency matrices for different types of graphs.

Uploaded by

wimaka7316
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)
11 views3 pages

Program 11

The document outlines a C program for creating a graph of cities using an adjacency matrix and implementing a breadth-first search (BFS) to determine the reachability of nodes from a given source. It includes code for inputting the number of vertices, the adjacency matrix, and the source node, followed by the BFS algorithm to identify reachable nodes. Additionally, it provides examples of adjacency matrices for different types of graphs.

Uploaded by

wimaka7316
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/ 3

Program 11

Develop a Program in C for the following operations on Graph(G)


of Cities
a. Create a Graph of N cities using Adjacency Matrix.
b. Print all the nodes reachable from a given starting node in a
digraph using DFS/BFS method

#include<stdio.h>
#include<stdlib.h>
#define SIZE 20
void bfs(int, int, int [][SIZE], int []);
int main()
{
int n,amat[SIZE][SIZE],source,visited[SIZE]={0},i,j;
printf("Enter number of vertices:\n");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for(i=0; i<n; i++)
for(j=0; j<n; j++)
scanf("%d", &amat[i][j]);
printf("The adjacency matrix is:\n");
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
printf("%d\t", amat[i][j]);
printf("\n");
}

printf("Give the source:\n");


scanf("%d", &source);

bfs(n, source, amat, visited);

for(i=0;i<n;i++)
if(visited[i]==0)
printf("%d is not reachable\n", i);
else
printf("%d is reachable\n",i);
return 0; }
1
void bfs(int n, int source, int amat[][SIZE], int visited[])
{
int q[SIZE], r=0, f=0, u, v;
visited[source]=1;
q[r]=source;
while(f<=r)
{
u= q[f++];
for(v=0;v<n;v++)
{
if((amat[u][v]==1)&(visited[v]==0))
{
q[++r]=v;
visited[v]=1;
}
}
}
}

Graph G1
4 1
0 1 1 1
non directional graph
1 0 1 1
1 1 0 1 3
0
1 1 1 0

2
Graph G3 Di-graph
3
0 1 0 adjacency matrix
directed graph
1 0 1
0 0 0

2
Graph G4
8
0 1 1 0 0 0 0 0
1 0 0 1 1 0 0 0
1 0 0 0 0 1 1 0
0 1 0 0 0 0 0 1
0 1 0 0 0 0 0 1
0 0 1 0 0 0 0 1
0 0 1 0 0 0 0 1
0 0 0 1 1 1 1 0

You might also like