a) Write a C program that accepts the vertices and edges of a graph and stores it as an adjacency matrix. Display the adjacency matrix.
Solution:
#include<stdio.h>
void main()
{
int AdjMat[10][10], n;
printf("\nEnter Number of Vertices\n");
scanf("%d", &n);
read_graph(AdjMat, n);
printf("\n Given Adjacency Matrix is:\n");
display(AdjMat, n);
}
void display(int AdjMat[20][20],int n)
{
int i, j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d\t", AdjMat[i][j]);
}
printf("\n");
}
}
void read_graph(int AdjMat[20][20],int n)
{
int i, j;
char reply;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
AdjMat[i][j]=0;
else
{
printf("\n Vertices %d and %d are Adjacent?(Y||N)\n", i, j);
fflush(stdin);
scanf("%c", &reply);
if(reply=='y'||reply=='Y')
AdjMat[i][j]=1;
else
AdjMat[i][j]=0;
}
}
}
}
void main()
{
int AdjMat[10][10], n;
printf("\nEnter Number of Vertices\n");
scanf("%d", &n);
read_graph(AdjMat, n);
printf("\n Given Adjacency Matrix is:\n");
display(AdjMat, n);
}
void display(int AdjMat[20][20],int n)
{
int i, j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d\t", AdjMat[i][j]);
}
printf("\n");
}
}
void read_graph(int AdjMat[20][20],int n)
{
int i, j;
char reply;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(i==j)
AdjMat[i][j]=0;
else
{
printf("\n Vertices %d and %d are Adjacent?(Y||N)\n", i, j);
fflush(stdin);
scanf("%c", &reply);
if(reply=='y'||reply=='Y')
AdjMat[i][j]=1;
else
AdjMat[i][j]=0;
}
}
}
}
0 Comments:
Post a Comment