Adjacency matrix meaning and definition in DSA (original) (raw)
Last Updated : 23 Jul, 2025
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 vertices of a graph.

Graph representation of undirected graph to Adjacency Matrix

Graph representation of directed graph to Adjacency Matrix
Characteristics of the adjacency matrix are:
- The size of the matrix is determined by the number of vertices (or nodes) in a graph.
- The edges in the graph are represented as values in the matrix. In case of unweighted graphs, the values are 0 or 1. In case of weighted graphs, the values are weights of the edges if edges are present, else 0.
- 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 Floyd-Warshall algorithm
- **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.