In graph theory, an adjacency matrix is a square matrix used to represent a finite (and usually dense) graph. The elements of the matrix indicate whether pairs of vertices are adjacent or not, and in weighted graphs, they store the edge weights.
In many beginner-level tutorials, adjacency matrices are implemented using vector of vectors (nested dynamic arrays), but this approach has inefficiencies due to multiple memory allocations. C++23 introduces std::mdspan , which provides a more efficient way to handle multidimensional data structures without the overhead of nested containers.
In this blog post, we’ll explore various implementations of an adjacency matrix, starting with a basic approach and progressively improving it using std::mdspan .
Starting slow
Let’s start with a straightforward implementation using a vector of vectors to represent the adjacency matrix.
#include
" ); for ( const auto & row : g . getAdjacencyMatrix ()) { for ( T weight : row ) { if ( weight == Graph < T >:: INF ) std :: print ( " ∞ " ); else std :: print ( " {:3} " , weight ); } std :: println (); } }
The class represents an undirected weighted graph.
The adjacency matrix is initialized with INF (representing no direct connection between nodes).
(representing no direct connection between nodes). The diagonal elements are set to 0 since a node is always connected to itself.
... continue reading