An adjacency matrix is a square matrix of N x N size where N is the number of nodes in the graph and it is used to represent the connections between the edges of a graph.
Characteristics of the adjacency matrix are:
- The size of the matrix is determined by the number of vertices in the graph.
- The number of nodes in the graph determines the size of the matrix.
- The number of edges in the graph is simply calculated.
- If the graph has few edges, the matrix will be sparse.
How to build an Adjacency Matrix:
It is very easy and simple to construct an adjacency matrix for a graph there are certain steps given below that you need to follow:
- Create an n x n matrix where n is the number of vertices in the graph.
- Initialize all elements to 0.
- For each edge (u, v) in the graph, if the graph is undirected mark a[u][v] and a[v][u] as 1, and if the edge is directed from u to v, mark a[u][v] as the 1. (Cells are filled with edge weight if the graph is weighted)
Applications of the Adjacency Matrix:
- Graph algorithms: Many graph algorithms like Dijkstra’s algorithm, Floyd-Warshall algorithm, and Kruskal’s algorithm use adjacency matrices to represent graphs.
- Image processing: Adjacency matrices are used in image processing to represent the adjacency relationship between pixels in an image.
- Finding the shortest path between two nodes: By performing matrix multiplication on the adjacency matrix, one can find the shortest path between any two nodes in a graph.
Advantages of using Adjacency Matrix:
- An adjacency matrix is simple and easy to understand.
- Adding or removing edges from a graph is quick and easy.
- It allows constant time access to any edge in the graph.
Disadvantages of using Adjacency Matrix:
- It is inefficient in terms of space utilisation for sparse graphs because it takes up O(N2) space.
- Computing all neighbors of a vertex takes O(N) time.