Article Directory
In this tutorial, you will learn what an adjacency matrix is. In addition, you will also find examples of adjacency matrices in C.
The adjacency matrix is a method of expressing the graph G={V,E} as a Boolean matrix.
Adjacency matrix notation
The size of the matrix is VxV, where V is the number of vertices in the graph. According to whether there are edges from vertex i to vertex j, the value of entry Aij is 1 or 0.
Example of adjacency matrix
The figure below shows a graph and its equivalent adjacency matrix.
For undirected graphs, due to the existence of each edge (i, j), the matrix is symmetric about the diagonal, so there is also an edge (j, i).
Advantages of adjacency matrix
Basic operations such as adding edges, deleting edges, and checking whether there are edges from vertex i to vertex j are very time-saving routine operations.
If the graph is dense and the number of edges is large, the adjacency matrix is the first choice. Even if the graph and the adjacency matrix are sparse, we can also use the data structure of the sparse matrix to represent it.
The biggest advantage of graphs comes from the use of matrices. The latest developments in hardware allow us to perform expensive matrix operations on the GPU.
By performing operations on the adjacency matrix, we can gain insight into the nature of the graph and the relationship between its vertices.
Disadvantages of adjacency matrix
The VxV space requirement of the adjacency matrix makes it occupy a lot of memory. Natural graphs usually don't have too many connections, which is the main reason why the adjacency list is a better choice for most tasks.
Although the basic operations are very simple, when using the adjacency matrix representation, operations such as adding edges and deleting edges are very costly.
C example
If you know how to create a two-dimensional array, then you also know how to create an adjacency matrix.
// Adjacency Matrix representation in C
#include <stdio.h>
#define V 4
// Initialize the matrix to zero
void init(int arr[][V]) {
int i, j;
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
arr[i][j] = 0;
}
// Add edges
void addEdge(int arr[][V], int i, int j) {
arr[i][j] = 1;
arr[j][i] = 1;
}
// Print the matrix
void printAdjMatrix(int arr[][V]) {
int i, j;
for (i = 0; i < V; i++) {
printf("%d: ", i);
for (j = 0; j < V; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int main() {
int adjMatrix[V][V];
init(adjMatrix);
addEdge(adjMatrix, 0, 1);
addEdge(adjMatrix, 0, 2);
addEdge(adjMatrix, 1, 2);
addEdge(adjMatrix, 2, 0);
addEdge(adjMatrix, 2, 3);
printAdjMatrix(adjMatrix);
return 0;
}
Adjacency matrix application
- Create a routing table in the network
- Navigation task
Reference documents
[1]Parewa Labs Pvt. Ltd.Adjacency Matrix[EB/OL].https://www.programiz.com/dsa/graph-adjacency-matrix,2020-01-01.