Implement Adjacency Matrix or Adjacency Linked List for an undirected or directed graph.
/* Adjacency matrix of undirected graph */
#include
#include
void main()
{
int a[20][20], m, n, i, x, y, j;
clrscr();
printf("Enter total no. of nodes:\n");
scanf("%d",&n);
printf("Enter total no. of edges:\n");
scanf("%d",&m);
/*Initialization of adjacency matrix */
for(i=0;i {
for(j=0;j a[i][j]=0;
}
for(i=1;i<=m;i++)
{
printf("\n Enter nodes of the edge %d ",i);
scanf("%d %d",&x,&y);
a[x-1][y-1]=1;
a[y-1][x-1]=1;
}
printf("\nThe resultant matrix is:-\n");
for(i=0;i {
for(j=0;j printf("%5d",a[i][j]);
printf("\n");
}
getch();
}
OUTPUT:-
Enter total no. of nodes:
4
Enter total no. of edges:
5
Enter nodes of the edge 1 1 3
Enter nodes of the edge 2 3 4
Enter nodes of the edge 3 4 2
Enter nodes of the edge 4 2 1
Enter nodes of the edge 5 1 4
The resultant matrix is:-
0 1 1 1
1 0 0 1
1 0 0 1
1 1 1 0
/* Adjacency matrix of undirected graph */
#include
#include
void main()
{
int a[20][20], m, n, i, x, y, j;
clrscr();
printf("Enter total no. of nodes:\n");
scanf("%d",&n);
printf("Enter total no. of edges:\n");
scanf("%d",&m);
/*Initialization of adjacency matrix */
for(i=0;i
for(j=0;j
}
for(i=1;i<=m;i++)
{
printf("\n Enter nodes of the edge %d ",i);
scanf("%d %d",&x,&y);
a[x-1][y-1]=1;
a[y-1][x-1]=1;
}
printf("\nThe resultant matrix is:-\n");
for(i=0;i
for(j=0;j
printf("\n");
}
getch();
}
OUTPUT:-
Enter total no. of nodes:
4
Enter total no. of edges:
5
Enter nodes of the edge 1 1 3
Enter nodes of the edge 2 3 4
Enter nodes of the edge 3 4 2
Enter nodes of the edge 4 2 1
Enter nodes of the edge 5 1 4
The resultant matrix is:-
0 1 1 1
1 0 0 1
1 0 0 1
1 1 1 0