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
Matrix Representation of Graphs
A graph can be represented using an Adjacency Matrix, which is a 2D array that stores the connection information between vertices.
Adjacency Matrix
An Adjacency Matrix A[V][V] is a 2D array of size V × V where V is the number of vertices in the graph. For an undirected graph, if there is an edge between Vx and Vy, then A[Vx][Vy] = 1 and A[Vy][Vx] = 1 (symmetric matrix). 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 adjacency matrix of an undirected graph is always symmetric (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 adjacency matrix of a directed graph is generally not symmetric, since an edge from a to b does not imply an edge from b to a.
Conclusion
An adjacency matrix provides a simple and efficient way to represent a graph, with O(1) edge lookup time. However, it uses O(V²) space, making it more suitable for dense graphs. For sparse graphs, an adjacency list is often more space-efficient.
