Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j. Adjacency matrix for undirected graph is always symmetric. Adjacency Matrix is also used to represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with weight w.
In case of an undirected graph, we need to show that there is an edge from vertex i to vertex j and vice versa. In code, we assign adj[i][j] = 1 and adj[j][i] = 1
In case of a directed graph, if there is an edge from vertex i to vertex j then we just assign adj[i][j]=1
The adjacency matrix for the above example graph is:

Pros: Representation is easier to implement and follow. Removing an edge takes O(1) time. Queries like whether there is an edge from vertex ‘u’ to vertex ‘v’ are efficient and can be done O(1).
Cons: Consumes more space O(V^2). Even if the graph is sparse(contains less number of edges), it consumes the same space. Adding a vertex is O(V^2) time. Computing all neighbors of a vertex takes O(V) time (Not efficient).
Please see this for a sample Python implementation of adjacency matrix.
Code (Github)
#include <iostream>
#include <vector>
using namespace std;
int main() {
// n is the number of vertices, m is the number of edges
int n, m;
cout << "Enter number of vertices and edges: ";
cin >> n >> m;
// Initialize an (n+1)x(n+1) adjacency matrix with zeros
vector<vector<int>> adjMat(n + 1, vector<int>(n + 1, 0));
cout << "Enter the edges (u, v):" << endl;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
adjMat[u][v] = 1;
adjMat[v][u] = 1; // Comment this line for a directed graph
}
// Display the adjacency matrix
cout << "\nAdjacency Matrix:" << endl;
cout << " "; // Align column headers
for (int i = 1; i <= n; i++) {
cout << i << " ";
}
cout << endl;
for (int i = 1; i <= n; i++) {
cout << i << " ";
for (int j = 1; j <= n; j++) {
cout << adjMat[i][j] << " ";
}
cout << endl;
}
return 0;
}
Try this input:
5 6
1 5
2 3
3 4
5 2
1 3
4 2
