Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Representation of Graphs
There are mainly two ways to represent a graph in computer science −
- Adjacency Matrix − A 2D array showing connections between vertices.
- Adjacency List − An array of linked lists showing neighbors of each vertex.
Adjacency Matrix
An adjacency matrix A[V][V] is a 2D array of size V × V where V is the number of vertices. For an undirected graph, if there is an edge between Vx and Vy, then A[Vx][Vy] = 1 and A[Vy][Vx] = 1 (the matrix is symmetric). For a directed graph, if there is an edge from Vx to Vy, then only A[Vx][Vy] = 1. Otherwise, the value is 0.
Adjacency Matrix of an Undirected Graph
Consider the following undirected graph ?
The adjacency matrix of the above undirected graph is −
| a | b | c | d | |
|---|---|---|---|---|
| a | 0 | 1 | 1 | 0 |
| b | 1 | 0 | 1 | 0 |
| c | 1 | 1 | 0 | 1 |
| d | 0 | 0 | 1 | 0 |
Note − The matrix is symmetric for undirected graphs (A[i][j] = A[j][i]).
Adjacency Matrix of a Directed Graph
Consider the following directed graph ?
The adjacency matrix of the above directed graph is −
| a | b | c | d | |
|---|---|---|---|---|
| a | 0 | 1 | 1 | 0 |
| b | 0 | 0 | 1 | 0 |
| c | 0 | 0 | 0 | 1 |
| d | 0 | 0 | 0 | 0 |
Note − The matrix is not symmetric for directed graphs. A[a][b] = 1 does not mean A[b][a] = 1.
Adjacency List
In the adjacency list representation, an array A[V] of linked lists is used. Each entry A[Vx] contains the list of all vertices adjacent to vertex Vx. This representation is more memory-efficient for sparse graphs (graphs with fewer edges).
The adjacency list for the undirected graph above is −
Comparison
| Feature | Adjacency Matrix | Adjacency List |
|---|---|---|
| Space complexity | O(V2) | O(V + E) |
| Edge lookup | O(1) | O(degree) |
| Best for | Dense graphs | Sparse graphs |
Conclusion
An adjacency matrix uses a V × V array for constant-time edge lookup but requires more space. An adjacency list uses linked lists for each vertex and is more memory-efficient for sparse graphs. Choose the representation based on the density of the graph and the operations you need to perform.
