Adjacency matrix

On this page 8

An adjacency matrix is a square two-dimensional array that represents a graph with n vertices as an n × n grid, where the cell in row i and column j records whether an edge connects vertex i to vertex j, and often the weight of that edge. Among the data structures used in programming for graphs, it offers constant-time edge lookup at the cost of quadratic memory, which makes it the natural counterpart of the adjacency list.

The choice between the two representations shapes the running time of nearly every graph algorithm, so understanding the matrix layout, its memory profile and its hardware behavior is a practical skill rather than a theoretical one.

How an adjacency matrix encodes a graph

An adjacency matrix encodes a graph by assigning each vertex an integer index from 0 to n − 1 and using those indices as row and column coordinates. For an unweighted graph, a cell holds 1 (or true) when the edge exists and 0 (or false) when it does not. For a weighted graph, the cell stores the edge weight, and a sentinel value such as infinity, a null marker or zero marks a missing edge.

The structure of the matrix mirrors the structure of the graph. An undirected graph produces a symmetric matrix, because the edge between i and j appears at both (i, j) and (j, i). A directed graph has no such guarantee: row i lists outgoing edges and column i lists incoming edges. The main diagonal records self-loops and is usually all zeros in simple graphs.

The following table shows how common graph variants map onto matrix cell contents.

Graph typeCell value when edge existsCell value when absentMatrix property
Undirected, unweighted1 or true0 or falseSymmetric
Directed, unweighted1 or true0 or falseGenerally asymmetric
WeightedEdge weightInfinity or nullSymmetric only if undirected
MultigraphNumber of parallel edges0Integer counts
Graph with self-loopsNonzero diagonal entry0 on diagonalDiagonal carries meaning
Cell conventions for common graph types

Time and space complexity of matrix operations

The defining performance trait of an adjacency matrix is O(1) edge testing combined with O(n²) space, regardless of how many edges the graph actually contains. Checking whether vertices u and v are connected is a single indexed read, but enumerating the neighbors of one vertex requires scanning an entire row of n cells, even when that vertex has only two neighbors.

The table below summarizes the cost of typical operations and contrasts each one with the adjacency list, where V is the vertex count and E is the edge count.

OperationAdjacency matrixAdjacency listPractical consequence
Test edge (u, v)O(1)O(degree of u)Matrix wins for frequent lookups
List neighbors of uO(V)O(degree of u)List wins on sparse graphs
Add or remove edgeO(1)O(1) to O(degree)Matrix is simpler to update
Add a vertexO(V²) to resizeO(1) amortizedMatrix suits fixed vertex sets
MemoryO(V²)O(V + E)Matrix wastes space on sparse graphs
Full traversal (BFS, DFS)O(V²)O(V + E)List is faster unless the graph is dense
Operation costs compared with an adjacency list

These costs explain why graph density is the deciding factor. When E approaches V², the matrix and the list consume comparable memory, and the matrix gains from contiguous storage and predictable access patterns. When E is closer to V, the matrix spends most of its memory recording absent edges.

Memory layout and storage variants

The physical layout of an adjacency matrix determines its real memory footprint, and several variants reduce the quadratic cost without changing the logical model. A naive implementation using an array of arrays of 32-bit integers needs 4n² bytes, so a graph with 100,000 vertices would require about 40 GB, which is impractical on ordinary hardware.

Engineers therefore choose a storage variant that matches the graph and the workload, as the next table shows.

VariantBytes per cellBest suited forMain limitation
Flat row-major array1 to 8Dense weighted graphsFull quadratic footprint
Bit matrix (bitset)1/8Dense unweighted graphsNo weights, bitwise code
Upper triangular storageHalf the full sizeUndirected graphsIndex arithmetic on every access
Sparse formats (CSR, COO)Proportional to edgesLarge sparse graphsSlower single-edge updates
Storage variants and their trade-offs

A flat one-dimensional array indexed as i × n + j usually outperforms nested arrays, because it keeps rows contiguous in memory and avoids pointer indirection. A bit matrix packs 64 edges into one machine word, which lets algorithms compute set intersections of neighborhoods with a single bitwise AND, a technique used in clique search and triangle counting.

Algorithms that favor the matrix representation

Some graph algorithms are naturally expressed on an adjacency matrix and gain little from a list. The Floyd–Warshall algorithm for all-pairs shortest paths runs in O(V³) time and updates a distance matrix in place, so starting from a weighted adjacency matrix is the standard approach. Dense implementations of Prim’s algorithm also run in O(V²) on a matrix, which beats heap-based versions on dense graphs.

The matrix also connects graph theory with linear algebra. Raising an unweighted adjacency matrix A to the power k yields a matrix whose entry (i, j) equals the number of walks of length k from i to j. Spectral methods study the eigenvalues of A or of the related Laplacian matrix to detect communities, measure connectivity and partition graphs, which is why numerical libraries treat graphs as matrices.

  • Transitive closure with Warshall’s algorithm operates directly on a boolean matrix.
  • Triangle counting can use the trace of A³ divided by six for undirected graphs.
  • Graph neural networks multiply feature matrices by a normalized adjacency matrix in each layer.
  • Small fixed graphs, such as state machines or game boards, benefit from simple indexed code.

Choosing between a matrix and other graph representations

The correct representation depends on density, vertex count and dominant operations. The adjacency matrix is rarely the default for large real-world graphs, such as social networks or road maps, because these graphs are overwhelmingly sparse. It remains the better choice for small or dense graphs and for workloads dominated by edge queries.

SituationRecommended structureReason
Under a few thousand vertices, denseAdjacency matrixFast lookup, modest memory
Millions of vertices, sparseAdjacency list or CSRMemory proportional to edges
Frequent edge existence queriesAdjacency matrix or hash setConstant-time checks
Traversal-heavy workloadAdjacency listNeighbor iteration without scanning
Linear algebra or GPU processingDense or sparse matrixLibrary and hardware support
Decision guide for graph representations

A useful rule of thumb is to estimate the fill ratio, E divided by V². When it exceeds roughly one quarter, a matrix is usually competitive; below about one percent, a list or a sparse matrix format is almost always better. Between those values, measured benchmarks on the target hardware should decide.

Common mistakes and limitations

Most problems with adjacency matrices come from underestimating memory growth or from ambiguous cell semantics. Because the footprint grows with the square of the vertex count, a prototype that works with 1,000 vertices may fail with out-of-memory errors at 50,000 vertices.

  • Using 0 as both weight and absence hides zero-weight edges; a separate sentinel avoids the ambiguity.
  • Updating only one cell in an undirected graph breaks symmetry and produces inconsistent traversals.
  • Iterating columns in a row-major array causes cache misses and can slow loops severalfold.
  • Resizing for new vertices copies the whole matrix, so dynamic vertex sets need preallocation or another structure.

The short version

An adjacency matrix is like a mileage chart in a road atlas. Every city appears once along the top and once down the side, and the box where a row meets a column tells you whether the two cities are directly connected, or how far apart they are.

The advantage is speed: you can answer any yes-or-no connection question instantly by looking at one box. The drawback is size, because the chart has a box for every possible pair, even when most pairs are not connected. That is why it works best for small or tightly connected networks.

Where it makes a difference

A logistics team plans deliveries between 40 regional warehouses, and almost every warehouse has a direct truck route to every other one. The developers store travel times in a 40 × 40 weighted adjacency matrix of 1,600 cells, which occupies only a few kilobytes.

Each night, the planning service runs the Floyd–Warshall algorithm on the matrix to compute the fastest route between every pair of warehouses, about 64,000 inner-loop updates that finish in well under a millisecond. When a road closure is reported, the team changes a single cell and reruns the computation.

The result is a complete, always current routing table that the dispatch application queries in constant time. Had the network contained 200,000 sparse delivery points instead, the same design would have required tens of gigabytes, and an adjacency list with Dijkstra’s algorithm would have been the appropriate choice.