Graph-Adjacency Matrix
Learn Theory-Graph Representations
/* Graph representation using adjacency matrix and finding the degree */
#include <stdio.h>
int adj[50][50],n;
void read()
{ int ad;
printf("Enter the Number of vertices\n");
scanf("%d",&n);
// storing element from [1][1]
//// assuming the vertices are numbered v1 v2..vn and we will enter only the index 1,2...n
for(int i=1;i<=n;i++)
{
printf("Enter the list of vertices adjacent to v%d -1 to stop\n",i);
while(1)
{
scanf("%d",&ad);
if(ad==-1) break;
adj[i][ad]=1;
}
}
}//end of read
void disp()
{
printf("Adjacency Matrix..\n");
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
printf("%5d",adj[i][j]);
printf("\n");
}
}
void calculateDegree() {
int i, j;
printf("Vertex\tDegree\n");
for (i = 1; i <=n; i++) {
int degree = 0;
for (j = 1; j <= n; j++) {
if (adj[i][j] == 1) {
degree++;
}
}
printf("v%ddegree=%d\n", i + 1, degree);
}
}
int main()
{
read();
disp();
calculateDegree();
return 0;
}
Comments
Post a Comment