An adjacency matrix is a boolean matrix that represents a Graph. Entry is if there’s an edge from vertex to vertex , and otherwise.
For weighted graphs, holds the edge weight (with or used as a sentinel for “no edge,” depending on the algorithm’s needs).
Properties
- Size: regardless of edge count. If you have 1000 vertices and 5 edges, the matrix is still 1,000,000 entries.
- Symmetric for undirected graphs: since edges go both ways.
- Asymmetric for directed graphs: doesn’t imply .
- Diagonal: represents a self-loop (an edge from a vertex to itself). Usually 0 in graphs without self-loops.
Operations
| Operation | Complexity |
|---|---|
| Check if edge exists | |
| Add edge | |
| Remove edge | |
| Iterate all neighbors of | |
| Total space |
The killer feature is constant-time edge lookup — you index directly into the matrix. The cost is the space.
Implementation
A 2D array, typically:
int adj[MAX_V][MAX_V] = {0}; // initially all zeros
void addEdge(int u, int v, bool directed) {
adj[u][v] = 1;
if (!directed) adj[v][u] = 1;
}
bool hasEdge(int u, int v) {
return adj[u][v] == 1;
}For weighted graphs, replace int adj[][] with weights, and use a sentinel like INT_MAX to mean “no edge.”
When to use
Adjacency matrices win when:
- The graph is dense — . The matrix isn’t wasting space because most cells are full.
- Edge lookup is frequent and order-independent. matters when you check edges constantly.
- The graph is small — say, 100 vertices. The cells are negligible.
- You need matrix operations: graph algorithms based on matrix multiplication (transitive closure via boolean matrix powers, BFS via matrix-vector products) work directly on adjacency matrices.
When not to use
- Sparse graphs — most real-world graphs have . A social network with millions of users and dozens of friends each is over 99% empty in matrix form.
- Memory-constrained scenarios — large makes prohibitive.
In these cases, see Adjacency list.
Effect on algorithms
BFS and DFS both run in on an adjacency matrix — for each vertex, you scan all possible neighbors. With an adjacency list, the same algorithms run in .
Some algorithms naturally work better with one representation:
- Dijkstra on dense graphs: matrix is fine.
- BFS/DFS on social networks: list is much better.
- Floyd-Warshall (all-pairs shortest paths): matrix-based, regardless of .
For the alternative representation that scales to sparse graphs, see Adjacency list. For graph fundamentals, see Graph.