DSA Program 11
DSA Program 11
Design, Develop and Implement 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.
C Program:
#include<stdio.h>
int visited[10],a[10][10],n;
void main()
{
int i,j,source;
clrscr();
printf("Enter the number of cities\n");
scanf("%d",&n);
printf("Enter the adjacency matrix\n");
printf("0 if there is no path, 1 if there is a path\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("Enter the source city\n");
scanf("%d",&source);
for(i=1;i<=n;i++)
visited[i]=0;
dfs(source);
for(i=1;i<=n;i++)
{
if(visited[i]==0)
printf("node %d is not reachable\n",i);
else
printf("node %d is reachable\n",i);
}
}
OUTPUT 1:
Enter the number of cities
4
Enter the adjacency matrix
0 if there is no path, 1 if there is a path
0 1 0 0
0 0 1 1
1 0 0 0
0 0 0 0
Enter the source city
3
node 1 is reachable
node 2 is reachable
node 3 is reachable
node 4 is reachable
OUTPUT 2:
Enter the number of cities
4
Enter the adjacency matrix
0 if there is no path, 1 if there is a path
0 1 0 0
0 0 1 1
1 0 0 0
0 0 0 0
Enter the source city
3
node 1 is not reachable
node 2 is not reachable
node 3 is not reachable
node 4 is reachable
OUTPUT 3:
Enter the number of cities
4
Enter the adjacency matrix
0 if there is no path, 1 if there is a path
0 1 0 0
0 0 1 1
1 0 0 0
0 0 0 0
Enter the source city
2
node 1 is reachable
node 2 is reachable
node 3 is reachable
node 4 is reachable
OUTPUT 4:
Enter the number of cities
4
Enter the adjacency matrix
0 if there is no path, 1 if there is a path
0 1 1 0
0 0 0 0
0 0 0 0
0 1 1 0
Enter the source city
2
node 1 is not reachable
node 2 is reachable
node 3 is not reachable
node 4 is not reachable
OUTPUT 5:
Enter the number of cities
4
Enter the adjacency matrix
0 if there is no path, 1 if there is a path
0 1 1 0
0 0 0 0
0 0 0 0
0 1 1 0
Enter the source city
1
node 1 is reachable
node 2 is reachable
node 3 is reachable
node 4 is not reachable
OUTPUT 6:
Enter the number of cities
5
Enter the adjacency matrix
0 if there is no path, 1 if there is a path
0 0 1 1 1
1 0 1 0 0
0 0 0 0 0
0 0 0 0 1
0 0 1 0 0
Enter the source city
1
node 1 is reachable
node 2 is not reachable
node 3 is reachable
node 4 is reachable
node 5 is reachable