Adjacency Matrix implementation
What you'll learn: How to represent connections between objects using a simple 2D array.
The Social Grid
Imagine you are organizing a small dinner party with four guests: Alice, Bob, Charlie, and Diana. You want a quick way to track who knows whom.
You could draw a map with lines (a graph), or you could create a grid. In this grid, both the rows and columns represent your guests. If Alice knows Bob, you put a 1 where Alice’s row meets Bob’s column. If they are strangers, you put a 0. In computer science, this grid is called an Adjacency Matrix.
Implementing the Matrix
In C, the easiest way to build this grid is with a two-dimensional array. If we have nodes (guests), we create an array of size [N][N].
Here is how you initialize and fill a matrix for a graph with 4 nodes:
#include <stdio.h>
#define V 4 // Number of vertices
int main() {
// Initialize a 4x4 matrix with all zeros (no connections)
int adjMatrix[V][V] = {0};
// Add an edge between node 0 and node 1
// We set both directions to 1 for an undirected graph
adjMatrix[0][1] = 1;
adjMatrix[1][0] = 1;
// Add an edge between node 2 and node 3
adjMatrix[2][3] = 1;
adjMatrix[3][2] = 1;
// Printing the matrix to see the connections
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
printf("%d ", adjMatrix[i][j]);
}
printf("\n");
}
return 0;
}
Why use a Matrix?
The Adjacency Matrix is incredibly fast for one specific question: "Are A and B connected?"
To find the answer, the computer doesn't have to search through a list. It simply looks at the coordinates matrix[A][B]. If it sees a 1, the answer is yes. This "lookup" happens in constant time, meaning it’s just as fast whether you have 10 nodes or 10,000.
However, there is a trade-off. Even if your guests are all strangers and there are zero connections, the matrix still takes up space for every possible pairing. This makes it perfect for "dense" graphs where most things are connected, but a bit wasteful for "sparse" graphs where connections are rare.
Key takeaway
An Adjacency Matrix uses a 2D array to store graph connections, offering instant lookups at the cost of higher memory usage.