C Program To Read The Adjecancy Matrix of Directed Graph And Convert It Into Adjecancy List

How to Write a C Program to read the adjecancy matrix of directed graph and convert it into adjecancy list in C Programming Language ?


Solution:
/*write a c program to read the adjecancy matrix of directed graph
and convert it into adjecancy list*/


#include<stdio.h>
#include<conio.h>
void main()
{
int edges,i,j,tail,head,gtype,adj[10][10],n;
clrscr();
printf("Enter number of nodes : ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
adj[i][j]=0;  //Initialize the array of n*n size with 0
}
}
edges=n*(n-1);  //maximum no. of edges in directed
printf("\nEnter -1 -1 to exit\n\n");
for(i=1;i<=edges;i++)
{
printf("Edge %d : ",i);
scanf("%d %d",&tail,&head);
if(tail==-1||head==-1)
break;
if(tail>n||head>n||tail<=0||head<=0)
{
printf("Invalid edge!\n");
i--;
}
else
adj[tail][head]=1;
}
printf("\nAdjacency Matrix \n\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("\t%d",adj[i][j]);
}
printf("\n");
}
getch();
}


/*
Output for the Program Given in 6.1.3.1.A

Enter number of nodes : 3
1) Directed
2) Undirected
Choice : 1

Enter -1 -1 to exit

Edge 1 : 1 2
Edge 2 : 2 3
Edge 3 : 3 1
Edge 4 : 3 2
Edge 5 : -1 -1

Adjacency Matrix

 0 1 0
 0 0 1
 1 1 0
*/

/*
Output for the Program Given in 6.1.3.1.A

Enter number of nodes : 3
1) Directed
2) Undirected
Choice : 2
Enter -1 -1 to exit

Edge 1 : 1 2
Edge 2 : 2 3
Edge 3 : 3 1

Adjacency Matrix

 0 1 1
 1 0 1
 1 1 0
*/


Learn More :