EXPERIMENT NO.
7
Aim: Implementation of adjacency matrix creation.
Theory :
The following two are the most commonly used representations of a graph.
1. Adjacency Matrix
2. Adjacency List
There are other representations also like, Incidence Matrix and Incidence List. The choice of graph
representation is situation-specific. It totally depends on the type of operations to be performed
and ease of use.
An adjacency matrix is used to represent which nodes are adjacent to one another. By definition,
two nodes are said to be adjacent if there is an edge connecting them.
In a directed graph G, if node v is adjacent to node u, then there is definitely an edge from u to v.
That is, if v is adjacent to u, we can get from u to v by traversing one edge. For any graph G having
n nodes, the adjacency matrix will have the dimension of n ¥ n. In an adjacency matrix, the rows
and columns are labelled by graph vertices. An entry aij in the adjacency matrix will contain 1, if
vertices vi and vj are adjacent to each other. However, if the nodes are not adjacent, aij will be set
to zero. Since an adjacency matrix contains only 0s and 1s, it is called a bit matrix or a Boolean
matrix. The entries in the matrix depend on the ordering of the nodes in G. Therefore, a change in
the order of nodes will result in a different adjacency matrix.
Adjacency matrix entry
Some graphs and their corresponding adjacency matrices:
b) Undirected Graph
c) Weighted Graph
For a simple graph (that has no loops), the adjacency matrix has 0s on the diagonal.
Σ The adjacency matrix of an undirected graph is symmetric.
Σ The memory use of an adjacency matrix is O(n2), where n is the number of nodes in the graph.
Σ Number of 1s (or non-zero entries) in an adjacency matrix is equal to the number of edges in
the graph.
Σ The adjacency matrix for a weighted graph contains the weights of the edges connecting the
nodes.
SAMPLE PROGRAM FOR IMPLEMENTATION OF ADJACENCY MATRIX CREATION:
#include<stdio.h>
#define MAX 100
int adj[MAX][MAX]; /*Adjacency matrix*/
int n; /*Number of vertices in the graph*/
main()
{
int max_edges,i,j,origin,destin;
int graph_type;
printf("Enter 1 for undirected graph or 2 for directed graph : ");
scanf("%d",&graph_type);
printf("Enter number of vertices : ");
scanf("%d",&n);
if(graph_type==1)
max_edges = n*(n-1)/2;
else
max_edges = n*(n-1);
for(i=1; i<=max_edges; i++)
{
printf("Enter edge %d( -1 -1 to quit ) : ",i);
scanf("%d %d",&origin,&destin);
if( (origin == -1) && (destin == -1) )
break;
if( origin>=n || destin>=n || origin<0 || destin<0 )
{
printf("Invalid vertex!\n");
i--;
}
else
{
adj[origin][destin] = 1;
if( graph_type == 1) /*if undirected graph*/
adj[destin][origin] = 1;
}
}/*End of for*/
printf("The adjacency matrix is :\n");
for(i=0; i<=n-1; i++)
{
for(j=0; j<=n-1; j++)
printf("%4d",adj[i][j]);
printf("\n");
}
}/*End of main()*/
SAMPLE OUTPUT:
Conclusion: Hence, we have successfully created of adjacency matrix.