Graph Data Structure: Adjacency Matrix and Adjacency List, BFS and DFS in C, C++, Java, Python and C#

How adjacency matrices and adjacency lists compare in memory, how BFS and DFS walk a graph, and why recursive DFS overflows the stack on long paths.

A network of pale gray pebbles joined by threads, with a blue path from a blue pebble on the left through three pebbles to a blue pebble on the right, and the pebbles one thread away from the start painted green.

A graph is the data structure you reach for when the relationships are the data. For 5,000 vertices, the sparse graph in the experiments below stores its edges in an adjacency list of 160 KB, while the same graph as an adjacency matrix costs 25 MB, most of it empty.

Make the graph dense and the comparison reverses: the list grows to 100 MB while the matrix stays at 25 MB. The representation decides the memory and the traversal cost before a single algorithm runs. And when a recursive DFS meets a 100,000-vertex path on a 1 MB stack, it crashes, while the iterative version walks the whole path without growing the call stack.

This guide implements an undirected graph as both an adjacency matrix and an adjacency list in C, C++, Java, Python and C#. It measures both representations on sparse and dense graphs and walks them with breadth-first and depth-first search. None of these standard libraries ships a graph container, so the adjacency list is usually a list of lists. Every program was built and tested on Ubuntu 24.04 under WSL2 and on Windows 11 with MSVC, Java, Python and .NET. All five languages print the same demo output byte for byte, and every output block below comes from a real run.

What Is a Graph?

A graph is a set of vertices connected by edges, and it stores relationships that have no natural order or hierarchy: who is connected to whom, which page links to which, which city has a road to which. The two common representations are the adjacency matrix, a V by V table of edge flags, and the adjacency list, one list of neighbors per vertex.

A graph has two numbers that decide everything: V, the number of vertices, and E, the number of edges. An undirected graph stores each edge once in the conceptual model and twice in most representations, because a vertex’s entry must point back. A directed graph stores each edge once and the reverse edge may not exist. A weighted graph attaches a cost to each edge, and then the traversal questions change from reachability to cost, which is where Dijkstra’s algorithm lives.

The two traversals answer different questions. Breadth-first search starts at a source, visits every vertex at distance one, then distance two, and so on, which gives the shortest path in an unweighted graph and the connected components.

Depth-first search follows one edge as far as it can go before backing up, which gives preorder and postorder orderings, cycle detection, topological order for directed acyclic graphs and maze solving. Both visit each vertex and each edge a constant number of times, so both are O(V + E) with an adjacency list. With a matrix, finding a vertex’s neighbors costs V per vertex, so traversal becomes O(V²) no matter how few edges there are. That is the measured difference in this article.

Representation is a memory decision as much as a speed decision. The matrix uses V² cells, which is fine at 100 vertices and impossible at 100,000. The list uses space proportional to E, which is tiny for a sparse graph and larger than the matrix for a dense one if the per-entry overhead outweighs the saved zeros. The Shortest Path article is where weighted graphs take over with Dijkstra, and Kruskal’s algorithm uses the connected-components question for spanning trees, while this article covers the representation, BFS and DFS.

The same graph in a drawing, a matrix and a list Five vertices, five edges, ten symmetric matrix cells and ten list entries. drawing 0 1 2 3 4 adjacency matrix 0 0 1 1 2 2 3 3 4 4 1 1 1 1 1 1 1 1 1 1 V x V cells, 10 set adjacency list 0 -> 1, 2 1 -> 0, 3 2 -> 0, 3 3 -> 1, 2, 4 4 -> 3 V lists, 2E entries The matrix answers has_edge in constant time and pays V squared cells; the list pays only the edges and scans a vertex.
Figure 1: Five vertices and five edges in three views. The matrix stores V squared cells and answers an edge query in constant time. The adjacency list stores each edge twice and holds one vertex’s neighbors in one row. The drawing is what BFS and DFS actually walk.

How This Was Measured

SettingValue
Date testedDecember 1, 2026
HardwareIntel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Windows 11 Education build 26300
Operating systemUbuntu 24.04.5 under WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39; Windows 11 for the MSVC, Java and .NET builds
CompilersGCC 13.3 and Clang 18.1.3 at -O2 and -O3 through CMake Release; MSVC 19.44 at /W4 /WX
Language runtimesOpenJDK 27.0.1.1 (the CI matrix covers 17, 21 and 25); CPython 3.14.6; .NET SDK 10.0.404
Representation experiment5,000 vertices: a sparse graph with 15,000 unique random edges and the complete dense graph with 12,497,500 edges
Depth experimentPath graphs of 10,000 and 100,000 vertices; the 100,000 case runs the recursive DFS in a forked child with a 1 MB stack limit
What is timedBuild, BFS and DFS calls on the two representations; edge generation is outside the timed regions
StatisticSingle run for each size and representation, milliseconds; allocated bytes counted structurally and verified against the allocations
CheckThe matrix and the list must produce the same BFS distance array for every graph

No CPU pinning or frequency scaling control was used, and the host runs other software, so timings are indicative for this machine and the ratios are the useful part. All numbers come from one machine and one WSL2 instance. The dense graph is complete by construction, so its edge count is fixed at V(V – 1) / 2 rather than random.

Three Representations and What They Cost

The adjacency matrix is a V by V table: matrix[u][v] is set when the edge exists, and for an undirected graph the table is symmetric, so the storage holds 2E set cells. Checking an edge is one array access, and removing an edge is one write. Iterating a vertex’s neighbors scans the whole row, which costs V even when the vertex has one neighbor. The memory is V² cells regardless of E, which is the matrix’s strength and its weakness: at 100,000 vertices a byte per cell is 10 GB, so the representation simply does not fit.

The adjacency list is one list per vertex, each holding that vertex’s neighbors. For an undirected graph every edge appears twice, so the storage is 2E entries plus V list headers. Checking an edge means searching one endpoint’s list, which costs the degree, or its logarithm when the list is kept sorted as in these examples. Iterating the neighbors costs exactly the degree, so traversal is O(V + E). The memory grows with E, which is why large sparse graphs use it.

The edge list, a flat array of pairs, is the third representation: cheapest to build and read from a file, and worst for lookups, since finding a vertex’s neighbors scans every edge.

OperationAdjacency matrixAdjacency listEdge list
MemoryO(V²)O(V + E)O(E)
has_edgeO(1)O(degree)O(E)
Neighbors of vO(V)O(degree)O(E)
BFS or DFSO(V²)O(V + E)O(V + E) after conversion
Add edgeO(1)O(1) amortized, O(degree) when kept sorted as hereO(1) amortized
Best forDense graphs, constant-time queriesSparse graphs, traversalBuilding and streaming

The demo graph below uses seven vertices and nine edges. Its matrix has 18 set cells because each undirected edge appears twice, and its lists together hold 18 entries for the same reason. Both representations answer the same reachability questions, and the traversals must agree on them.

BFS and DFS: Two Ways to Walk the Same Graph

Breadth-first search uses a queue. It marks the source visited, enqueues it, and repeatedly dequeues a vertex and enqueues every unvisited neighbor, marking each when it is enqueued. Because the queue serves vertices in the order they were discovered, the search reaches every vertex at distance d before any vertex at distance d + 1.

So the distance array it fills is the shortest-path distance in an unweighted graph and the visited set is exactly the source’s connected component. Repeating the search for every unvisited vertex counts the components.

Depth-first search uses a stack: the call stack in the recursive form, an explicit array in the iterative one. It marks the source, then follows one edge as far as possible, backtracking only when a vertex has no unvisited neighbor. The order in which vertices are first discovered is the preorder, and the order in which they finish is the postorder. The two orderings are the basis for cycle detection, topological sorting and strongly connected components.

The recursive form is the shortest code, but each level of depth costs a stack frame. A path graph of 100,000 vertices is 100,000 frames deep, which can exceed the stack: Windows gives a thread 1 MB by default and Linux typically 8 MB. The iterative form swaps the call stack for a vector that the program controls.

Both traversals need a visited marker. In BFS the marker must be set when a vertex is enqueued, not when it is dequeued, or a vertex with several neighbors is enqueued several times and the queue grows beyond V. In DFS the marker must be checked when a vertex is popped, or a cycle keeps pushing it. The pitfalls section demonstrates both, plus the matrix that stores an undirected edge only once.

Same graph, two walks from vertex 0 BFS colors vertices by distance; DFS numbers them in visit order. BFS from 0 0 d0 1 d1 2 d1 3 d2 4 d2 5 d2 6 d3 blue d0, green d1, amber d2, dark d3 DFS from 0 0 1 1 2 2 6 3 3 4 5 5 7 6 4 the number is the position in the preorder
Figure 2: The same seven-vertex graph walked twice from vertex 0. BFS colors vertices by distance (0, 1, 2, 3). DFS numbers them in preorder (0, 1, 3, 6, 4, 2, 5), following one branch to the end before the next.

Graph Implementation in C

The C version keeps both representations in one structure: a byte matrix of V by V cells and a list of adjacency arrays sized by vertex. The demo builds the seven-vertex graph, checks two edges through both representations, then runs BFS and DFS and counts components. The BFS queue is an array of vertex ids with head and tail indexes, and the DFS stack is a plain array with a top index.

bool graph_add_edge(Graph *graph, int u, int v)
{
    AdjList *from;
    AdjList *to;
    if (graph == NULL || graph->matrix == NULL || graph->lists == NULL)
        return false;
    if (!graph_valid_vertex(graph, u) || !graph_valid_vertex(graph, v))
        return false;
    if (u == v)
        return false;
    if (graph->matrix[(size_t)u * (size_t)graph->vertices + (size_t)v] != 0)
        return false;
    from = &graph->lists[u];
    to = &graph->lists[v];
    if (!adjacency_reserve(from, from->size + 1) ||
        !adjacency_reserve(to, to->size + 1))
        return false;
    adjacency_insert_at(from, adjacency_position(from, v), v);
    adjacency_insert_at(to, adjacency_position(to, u), u);
    graph->matrix[(size_t)u * (size_t)graph->vertices + (size_t)v] = 1;
    graph->matrix[(size_t)v * (size_t)graph->vertices + (size_t)u] = 1;
    graph->edges++;
    return true;
}
int graph_bfs(const Graph *graph, int source, int *order, int *distances)
{
    int vertices;
    int *queue = NULL;
    unsigned char *visited = NULL;
    int head = 0;
    int tail = 0;
    int reached = 0;
    int vertex;
    if (graph == NULL || order == NULL || distances == NULL)
        return -1;
    vertices = graph->vertices;
    if (!graph_valid_vertex(graph, source))
        return -1;
    queue = malloc((size_t)vertices * sizeof *queue);
    visited = calloc((size_t)vertices, sizeof *visited);
    if (queue == NULL || visited == NULL) {
        free(queue);
        free(visited);
        return -1;
    }
    for (vertex = 0; vertex < vertices; ++vertex)
        distances[vertex] = -1;
    visited[source] = 1;             /* marked when enqueued, not when dequeued */
    distances[source] = 0;
    queue[tail++] = source;
    while (head < tail) {
        int current = queue[head++];
        const AdjList *row = &graph->lists[current];
        size_t index;
        order[reached++] = current;
        for (index = 0; index < row->size; ++index) {
            int next = row->ids[index];
            if (!visited[next]) {
                visited[next] = 1;
                distances[next] = distances[current] + 1;
                queue[tail++] = next;
            }
        }
    }
    free(queue);
    free(visited);
    return reached;
}
int graph_dfs(const Graph *graph, int source, int *order)
{
    int vertices;
    int *stack = NULL;
    size_t stack_size = 0;
    size_t stack_capacity = 0;
    unsigned char *visited = NULL;
    int reached = 0;
    if (graph == NULL || order == NULL)
        return -1;
    vertices = graph->vertices;
    if (!graph_valid_vertex(graph, source))
        return -1;
    visited = calloc((size_t)vertices, sizeof *visited);
    if (visited == NULL)
        return -1;
    if (!stack_push(&stack, &stack_size, &stack_capacity, source)) {
        free(visited);
        return -1;
    }
    while (stack_size > 0) {
        int current = stack[--stack_size];
        const AdjList *row;
        size_t index;
        if (visited[current])
            continue;
        visited[current] = 1;
        order[reached++] = current;
        row = &graph->lists[current];
        for (index = row->size; index > 0; --index) {
            int next = row->ids[index - 1];
            if (!visited[next] &&
                !stack_push(&stack, &stack_size, &stack_capacity, next)) {
                free(stack);
                free(visited);
                return -1;
            }
        }
    }
    free(stack);
    free(visited);
    return reached;
}

The BFS loop is the whole algorithm: dequeue a vertex, scan its neighbors, mark and enqueue each unvisited one, and set its distance to the parent’s plus one. The DFS loop pushes neighbors in reverse id order so the smallest is popped next, which reproduces the recursive preorder without growing the call stack. Both traversals ask the adjacency list for neighbors, so they run in O(V + E). The matrix is there for the constant-time edge query and for the measured comparison.

Output:

undirected graph: 7 vertices, 9 edges
adjacency matrix: 7 x 7, 18 ones
adjacency list: 7 lists, 18 entries
edge 1-3: matrix true, list true
edge 0-3: matrix false, list false
BFS from 0: 0 1 2 3 4 5 6
BFS distances from 0: 0 1 1 2 2 2 3
DFS from 0: 0 1 3 6 4 2 5
components: 1

Graph Implementation in C++

The C++ version is a class with a std::vector<std::vector<unsigned char>> matrix and a std::vector<std::vector<int>> adjacency list. The matrix uses one byte per cell because std::vector<bool> packs bits behind proxy references, which complicates element access. BFS returns the visit order and a distance vector, DFS returns the preorder, and components repeats the iterative DFS from every unvisited vertex.

inline Graph::BfsResult Graph::bfs(int source) const
{
    BfsResult result;
    result.distance.assign(vertex_count_, -1);
    if (!valid_vertex(source))
        return result;
    std::queue<int> pending;
    result.distance[static_cast<std::size_t>(source)] = 0;
    result.order.push_back(source);
    pending.push(source);
    while (!pending.empty()) {
        const int vertex = pending.front();
        pending.pop();
        const int distance =
            result.distance[static_cast<std::size_t>(vertex)] + 1;
        // The row is ascending, so the neighbours are enqueued in ascending id
        // order and the visit order of each distance level is ascending too.
        for (const int neighbour : lists_[static_cast<std::size_t>(vertex)]) {
            if (result.distance[static_cast<std::size_t>(neighbour)] != -1)
                continue;
            result.distance[static_cast<std::size_t>(neighbour)] = distance;
            result.order.push_back(neighbour);
            pending.push(neighbour);
        }
    }
    return result;
}
inline std::vector<int> Graph::dfs_preorder(
    const std::vector<std::vector<int>>& adjacency, int source)
{
    std::vector<int> order;
    if (source < 0 || static_cast<std::size_t>(source) >= adjacency.size())
        return order;
    std::vector<unsigned char> visited(adjacency.size(), 0);
    visit_preorder(adjacency, source, visited, order);
    return order;
}
inline void Graph::visit_preorder(
    const std::vector<std::vector<int>>& adjacency,
    int source,
    std::vector<unsigned char>& visited,
    std::vector<int>& order)
{
    std::vector<int> stack;
    stack.push_back(source);
    while (!stack.empty()) {
        const int vertex = stack.back();
        stack.pop_back();
        if (visited[static_cast<std::size_t>(vertex)] != 0)
            continue;
        visited[static_cast<std::size_t>(vertex)] = 1;
        order.push_back(vertex);
        // Reverse iteration puts the smallest neighbour on top of the stack, so
        // it is popped first and the preorder matches the recursive preorder.
        const std::vector<int>& row = adjacency[static_cast<std::size_t>(vertex)];
        for (auto it = row.rbegin(); it != row.rend(); ++it) {
            if (visited[static_cast<std::size_t>(*it)] == 0)
                stack.push_back(*it);
        }
    }
}

The standard library has no graph container, and the standard answer is the adjacency list above. The Boost Graph Library provides one, with generic algorithms and property maps, but it is external, template-heavy, and out of scope for this article. The Boost Graph documentation is the place to start when the project already depends on Boost.

Graph Implementation in Java, Python and C#

The three versions follow the same design: a matrix for edge queries, a list of lists for traversal, BFS with a queue and distances, iterative DFS with an explicit stack, and a components loop. None of these languages ships a graph container in its standard library, so the list of lists is the default everywhere.

Java

    public boolean addEdge(int u, int v) {
        checkVertex(u);
        checkVertex(v);
        if (u == v || matrix[u][v] != 0) {
            return false;
        }
        matrix[u][v] = 1;
        matrix[v][u] = 1;
        insertSorted(adjacency.get(u), v);
        insertSorted(adjacency.get(v), u);
        edges++;
        return true;
    }
    public Bfs bfs(int source) {
        checkVertex(source);
        List<Integer> order = new ArrayList<>();
        int[] distances = new int[vertices];
        Arrays.fill(distances, -1);
        Deque<Integer> queue = new ArrayDeque<>();
        distances[source] = 0;      // the distance array doubles as the visited marker
        queue.add(source);
        while (!queue.isEmpty()) {
            int vertex = queue.remove();
            order.add(vertex);
            for (int neighbour : adjacency.get(vertex)) {
                if (distances[neighbour] < 0) {
                    distances[neighbour] = distances[vertex] + 1;
                    queue.add(neighbour);
                }
            }
        }
        return new Bfs(order, distances);
    }
    static List<Integer> depthFirstOrder(List<List<Integer>> adjacency, int source) {
        List<Integer> order = new ArrayList<>();
        boolean[] visited = new boolean[adjacency.size()];
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(source);
        while (!stack.isEmpty()) {
            int vertex = stack.pop();
            if (visited[vertex]) {
                continue;               // a cycle may have queued the vertex twice
            }
            visited[vertex] = true;
            order.add(vertex);
            List<Integer> neighbours = adjacency.get(vertex);
            for (int index = neighbours.size() - 1; index >= 0; index--) {
                stack.push(neighbours.get(index));   // reverse order: lowest id on top
            }
        }
        return order;
    }

Graph uses int[][] for the matrix and List<List<Integer>> for the adjacency lists, kept sorted. It exposes addEdge, hasEdgeMatrix, hasEdgeList, bfs (returning order and distances), dfs, components and the counts. Absence from the matrix is 0, and the README documents the simple-graph rules. JGraphT is the Java library for graphs with real algorithms: jgrapht.org has the full API and a gallery of examples.

Python

    def add_edge(self, u: int, v: int) -> bool:
        """Add the undirected edge once and report whether it was added.

        A self-loop, a duplicate edge and a vertex id outside the graph are
        ignored: the call reports False and changes nothing.
        """
        if not self._valid(u) or not self._valid(v):
            return False
        if u == v or self._matrix[u][v]:
            return False
        self._matrix[u][v] = True
        self._matrix[v][u] = True
        insort(self._adjacency[u], v)
        insort(self._adjacency[v], u)
        self._edge_count += 1
        return True
    def bfs(self, source: int) -> tuple[list[int], list[int]]:
        """Return the breadth-first visit order and the distances from source.

        Every reachable vertex is visited once, by non-decreasing distance and
        with neighbours in ascending id order.  The distance list holds -1 for
        every vertex the source cannot reach.  An out of range source returns
        an empty order with every distance -1.
        """
        distances = [-1] * self._vertex_count
        if not self._valid(source):
            return [], distances
        order: list[int] = []
        distances[source] = 0
        queue: deque[int] = deque([source])
        while queue:
            vertex = queue.popleft()
            order.append(vertex)
            next_distance = distances[vertex] + 1
            for neighbour in self._adjacency[vertex]:
                if distances[neighbour] < 0:
                    distances[neighbour] = next_distance
                    queue.append(neighbour)
        return order, distances
def iterative_dfs(adjacency: Sequence[Sequence[int]], source: int) -> list[int]:
    """Return the iterative depth-first preorder over sorted adjacency lists.

    The stack starts with the source.  A popped vertex that is already visited
    is skipped, otherwise it is marked and appended, and its unvisited
    neighbours are pushed in reverse ascending id order so the smallest id is
    popped first.  The result equals the recursive preorder when every list is
    sorted, and no call recurses, which is what makes a path of a million
    vertices safe.  This is the engine behind ``Graph.dfs``; it is public so
    that the deep path test can walk adjacency lists alone, without allocating
    a V by V matrix.
    """
    if not 0 <= source < len(adjacency):
        return []
    visited = [False] * len(adjacency)
    order: list[int] = []
    stack = [source]
    while stack:
        vertex = stack.pop()
        if visited[vertex]:
            continue
        visited[vertex] = True
        order.append(vertex)
        for neighbour in reversed(adjacency[vertex]):
            if not visited[neighbour]:
                stack.append(neighbour)
    return order

The Python class keeps the matrix as a list of lists of bool and the adjacency lists as a list of lists of int. BFS uses collections.deque, and the DFS stack is a list used with append and pop. Python’s standard library has no graph type, and NetworkX is the usual library when the project needs more than a list of lists: networkx.org documents the data structures and algorithms.

C#

    public bool AddEdge(int u, int v)
    {
        ValidateVertex(u, nameof(u));
        ValidateVertex(v, nameof(v));
        if (u == v || _matrix[u, v] != 0)
            return false;

        _matrix[u, v] = 1;
        _matrix[v, u] = 1;
        InsertSorted(_adjacency[u], v);
        InsertSorted(_adjacency[v], u);
        _edgeCount++;
        return true;
    }
    public (int[] Order, int[] Distances) Bfs(int source)
    {
        ValidateVertex(source, nameof(source));

        int[] distances = new int[VertexCount];
        Array.Fill(distances, -1);
        distances[source] = 0;

        var order = new List<int>(VertexCount);
        var queue = new Queue<int>();
        queue.Enqueue(source);
        while (queue.Count > 0)
        {
            int vertex = queue.Dequeue();
            order.Add(vertex);
            foreach (int neighbour in _adjacency[vertex])
            {
                if (distances[neighbour] >= 0)
                    continue;
                distances[neighbour] = distances[vertex] + 1;
                queue.Enqueue(neighbour);
            }
        }
        return (order.ToArray(), distances);
    }
    internal static int[] DfsOrder(List<List<int>> adjacency, int source)
    {
        bool[] visited = new bool[adjacency.Count];
        var order = new List<int>(adjacency.Count);
        var stack = new Stack<int>();
        stack.Push(source);
        while (stack.Count > 0)
        {
            int vertex = stack.Pop();
            if (visited[vertex])
                continue;

            visited[vertex] = true;
            order.Add(vertex);
            List<int> neighbours = adjacency[vertex];
            for (int index = neighbours.Count - 1; index >= 0; index--)
                stack.Push(neighbours[index]);
        }
        return order.ToArray();
    }

The C# class uses a byte[,] matrix, one byte per cell, and List<List<int>> for the adjacency lists. BFS uses Queue<int>, and Components walks each new component with a Stack<int>. QuikGraph is the C# library when a graph type and its algorithms are needed: QuikGraph on GitHub documents the API.

Sparse and Dense: The Measured Memory

The memory experiment builds both representations of the same two graphs at 5,000 vertices: a sparse graph with 15,000 unique random edges, and the complete graph with 12,497,500 edges. It reports the bytes each representation allocates and times the build of each. The matrix is counted at one byte per cell, and the list, stored as one flat array with per-vertex offsets, at its offsets plus two int entries per edge.

static void bfs_matrix(const MatrixGraph *graph, int source, int *distances,
                       int *queue, unsigned char *visited)
{
    int head = 0;
    int tail = 0;
    int vertex;
    for (vertex = 0; vertex < VERTICES; ++vertex)
        distances[vertex] = -1;
    memset(visited, 0, (size_t)VERTICES);
    visited[source] = 1;
    distances[source] = 0;
    queue[tail++] = source;
    while (head < tail) {
        int current = queue[head++];
        const unsigned char *row = &graph->matrix[(size_t)current * (size_t)VERTICES];
        int next;
        for (next = 0; next < VERTICES; ++next) {
            if (row[next] && !visited[next]) {
                visited[next] = 1;
                distances[next] = distances[current] + 1;
                queue[tail++] = next;
            }
        }
    }
}

/* BFS from source over the list, with the same mark-on-enqueue rule. */
static void bfs_list(const ListGraph *graph, int source, int *distances,
                     int *queue, unsigned char *visited)
{
    int head = 0;
    int tail = 0;
    int vertex;
    for (vertex = 0; vertex < VERTICES; ++vertex)
        distances[vertex] = -1;
    memset(visited, 0, (size_t)VERTICES);
    visited[source] = 1;
    distances[source] = 0;
    queue[tail++] = source;
    while (head < tail) {
        int current = queue[head++];
        size_t index = graph->offsets[current];
        for (; index < graph->offsets[current + 1]; ++index) {
            int next = graph->neighbours[index];
            if (!visited[next]) {
                visited[next] = 1;
                distances[next] = distances[current] + 1;
                queue[tail++] = next;
            }
        }
    }
}

Output:

5,000 vertices, undirected, no self-loops
graph    edges       matrix_bytes  list_bytes  build_matrix_ms  build_list_ms  bfs_matrix_ms  bfs_list_ms  dfs_matrix_ms  dfs_list_ms
sparse   15000       25000000      160008      2                0              16             0            16             0
dense    12497500    25000000      100020008   79               158            13             23           19             19
distances agree: true

At 5,000 vertices the matrix is 25,000,000 bytes for both graphs, because V squared cells do not care how many edges exist. The sparse graph’s adjacency list is 160,008 bytes, 156 times smaller, and the dense graph’s list is 100,020,008 bytes, four times larger than the matrix.

The crossover is arithmetic. The list pays 8 bytes per edge (two 4-byte neighbor ids) plus 40,008 bytes of offsets, so at this V it beats the matrix below about 3.1 million edges and loses above. The counts were verified against the allocation formulas, and the two representations produced the same BFS distance array. The matrix is a fixed V squared tax that is cheap when the graph is dense and ruinous when it is not. A bit-per-cell matrix would move the crossover down to about 390,000 edges without changing the shape of the argument.

Allocated bytes for 5,000 vertices Logarithmic scale. The matrix ignores the edge count; the list follows it. sparse graph: adjacency list 160 KB sparse graph: adjacency matrix 25.0 MB dense graph: adjacency list 100.0 MB dense graph: adjacency matrix 25.0 MB 10 KB 1 MB 100 MB allocated bytes (log scale) Sparse: 15,000 edges, list 160 KB against matrix 25.0 MB. Dense: 12,497,500 edges, list 100.0 MB against matrix 25.0 MB.
Figure 3: Allocated bytes for the two representations at 5,000 vertices, logarithmic scale. The sparse graph’s list is orders of magnitude smaller than the matrix, and the dense graph reverses the comparison because the matrix still costs V squared while the list grows with the edges.

BFS and DFS on Both Representations

The same experiment walks each graph with both representations: BFS from vertex 0 and iterative DFS from vertex 0, timed separately, and the two representations must produce the same distance array. The memory table above already explains most of the timings.

The sparse graph is where the matrix’s fixed tax shows. Its BFS and DFS took 16 ms each, while the list walked the same 15,000 edges in under a millisecond, because the matrix must check all 25 million cells to find them.

The dense graph reverses the comparison. The matrix’s BFS took 13 ms against the list’s 23 ms, and both DFS runs took 19 ms. The list now holds 24,995,000 entries, two per edge, so it does the same order of work as the matrix’s 25 million cell checks, and the matrix reads its byte rows with better locality than the list reads 4-byte ids. The zero entries mean under half a millisecond, not zero work. These are single runs, so the memory table and the O(V squared) against O(V + E) argument carry the comparison, and the timings show the direction at this size.

Recursive DFS Against a Long Path

The depth experiment runs three walks on path graphs. The iterative DFS visits a 100,000-vertex path and reports the largest the explicit stack ever grew. The recursive DFS visits a 10,000-vertex path on the default stack and reports its deepest frame. The recursive DFS on the 100,000-vertex path runs in a forked child whose stack is limited to 1 MB, so the crash is contained and the parent can report the signal instead of dying with it.

static void dfs_recursive(const size_t *offsets, const int *neighbours,
                          int vertex, unsigned char *visited, size_t depth,
                          size_t *visited_count, size_t *max_depth)
{
    size_t index;
    visited[vertex] = 1;
    (*visited_count)++;
    if (depth > *max_depth)
        *max_depth = depth;
    for (index = offsets[vertex]; index < offsets[vertex + 1]; ++index) {
        int next = neighbours[index];
        if (!visited[next]) {
            dfs_recursive(offsets, neighbours, next, visited, depth + 1,
                          visited_count, max_depth);
        }
    }
}

/* Iterative DFS with the article's explicit stack: push neighbours in reverse
 * ascending order, check visited when a vertex is popped, and report the
 * largest stack the run ever held. On this path only one entry is ever pending
 * at a time, whatever N is. The stack has room for the whole neighbour array,
 * which is the most a stack entry can ever be. */
static bool dfs_iterative(const size_t *offsets, const int *neighbours,
                          int vertices, int source, unsigned char *visited,
                          size_t *visited_count, size_t *max_stack)
{
    size_t *stack = malloc(2 * (size_t)vertices * sizeof *stack);
    size_t stack_size = 0;
    if (stack == NULL)
        return false;
    stack[stack_size++] = (size_t)source;
    if (stack_size > *max_stack)
        *max_stack = stack_size;
    while (stack_size > 0) {
        int current = (int)stack[--stack_size];
        size_t index;
        if (visited[current])
            continue;
        visited[current] = 1;
        (*visited_count)++;
        for (index = offsets[current + 1]; index > offsets[current]; --index) {
            int next = neighbours[index - 1];
            if (!visited[next]) {
                stack[stack_size++] = (size_t)next;
                if (stack_size > *max_stack)
                    *max_stack = stack_size;
            }
        }
    }
    free(stack);
    return true;
}

Output:

path graph, undirected
vertices  method                    stack_limit  visited  max_depth  result
10000     recursive DFS             default      10000    10000      complete
100000    recursive DFS             1 MB         -        -          crash (signal 11)
100000    iterative DFS             default      100000   1          complete

The recursive DFS on the 10,000-vertex path went 10,000 frames deep and completed on the default stack. The iterative version on 100,000 vertices visited every vertex, and its explicit stack never held more than one vertex because a path offers only one unvisited neighbor at each step.

The recursive version on the 100,000-vertex path, given a 1 MB stack, died on SIGSEGV, signal 11. That is a platform boundary, not an algorithmic one. Every recursion level costs a call frame, and a path graph is the worst case for depth. The explicit stack is not free in general, because a star graph can make it hold V vertices, but it is memory the program can account for and size, unlike the call stack.

Five Ways a Graph Traversal Passes a Quick Test and Still Fails

Each of these programs compiles cleanly with -Wall -Wextra -pedantic and prints something plausible until the line below it. The first four live in the C repository’s pitfalls/ directory and the fifth in the C++ repository’s, and the workflows re-run each and assert the line or sanitizer summary that shows the bug.

1. Visited When Dequeued Instead of Enqueued

int main(void)
{
    unsigned char adjacency[VERTICES][VERTICES] = { { 0 } };
    int queue[QUEUE_CAPACITY];
    unsigned char visited[VERTICES] = { 0 };
    int head = 0;
    int tail = 0;
    int queued = 0;
    int u;
    int v;

    for (u = 0; u < VERTICES; ++u) {
        for (v = u + 1; v < VERTICES; ++v)
            add_edge(adjacency, u, v);
    }

    printf("bfs_mark_on_dequeue: visited is marked when a vertex is dequeued\n");
    printf("%d vertices, complete graph, BFS from 0\n", VERTICES);

    queue[tail++] = 0;              /* source is enqueued, not yet marked */
    queued++;
    while (head < tail) {
        int current = queue[head++];
        int next;
        if (visited[current])
            continue;               /* the mark happened here, too late */
        visited[current] = 1;
        for (next = 0; next < VERTICES; ++next) {
            if (adjacency[current][next] && !visited[next] &&
                tail < QUEUE_CAPACITY) {
                queue[tail++] = next;   /* enqueued without a mark */
                queued++;
            }
        }
    }

    printf("BFS from 0 queued %d entries for %d vertices, expected %d\n",
           queued, VERTICES, VERTICES);
    return EXIT_SUCCESS;
}

Output:

bfs_mark_on_dequeue: visited is marked when a vertex is dequeued
4 vertices, complete graph, BFS from 0
BFS from 0 queued 7 entries for 4 vertices, expected 4

Marking a vertex when it is dequeued lets its neighbors enqueue it again before it is processed. On the four-vertex complete graph the queue processed seven entries for four vertices. The duplicate work grows with the number of edges, and on a large dense graph the queue can hold far more entries than there are vertices. The fix is one line: mark the vertex when it is enqueued, not when it is dequeued.

2. An Undirected Edge Stored in One Direction

static int bfs_reachable(unsigned char matrix[VERTICES][VERTICES], int source)
{
    int queue[QUEUE_CAPACITY];
    unsigned char visited[VERTICES] = { 0 };
    int head = 0;
    int tail = 0;
    int reached = 0;
    visited[source] = 1;
    queue[tail++] = source;
    while (head < tail) {
        int current = queue[head++];
        int next;
        reached++;
        for (next = 0; next < VERTICES; ++next) {
            if (matrix[current][next] && !visited[next] &&
                tail < QUEUE_CAPACITY) {
                visited[next] = 1;
                queue[tail++] = next;
            }
        }
    }
    return reached;
}

Output:

matrix_unsymmetric: add_edge writes only matrix[u][v]
3 vertices, edges 0-2 and 1-2
BFS from 2 reached 1 of 3 vertices, expected 3; components: 2, expected 1

An undirected edge must be written in both matrix cells. This program writes only matrix[u][v], so a traversal that starts at v cannot see u. The BFS from vertex 2 reached one of three vertices instead of three, and the component count came out two instead of one. A test that only checks an edge in the order it was added would never notice.

3. A DFS With No Visited Check

int main(void)
{
    unsigned char adjacency[VERTICES][VERTICES] = { { 0 } };
    int stack[STACK_CAPACITY];
    int stack_size = 0;
    int order[STACK_CAPACITY];
    int order_count = 0;
    int vertex;
    bool bounded = false;

    add_edge(adjacency, 0, 1);
    add_edge(adjacency, 1, 2);
    add_edge(adjacency, 2, 0);

    printf("dfs_no_visited: iterative DFS pushes neighbours without a visited check\n");
    printf("triangle 0-1-2, bounded at %d pops\n", MAX_POPS);

    stack[stack_size++] = 0;
    while (stack_size > 0) {
        int current;
        int next;
        if (order_count >= MAX_POPS) {
            bounded = true;
            break;
        }
        current = stack[--stack_size];
        order[order_count++] = current;     /* no visited array exists */
        for (next = 0; next < VERTICES; ++next) {
            if (adjacency[current][next] && stack_size < STACK_CAPACITY)
                stack[stack_size++] = next;
        }
    }

    printf("DFS order:");
    for (vertex = 0; vertex < order_count; ++vertex)
        printf(" %d", order[vertex]);
    printf(", expected 0 1 2 for %d vertices\n", VERTICES);
    printf("stopped by the bounded loop: %s\n", bounded ? "true" : "false");
    return EXIT_SUCCESS;
}

Output:

dfs_no_visited: iterative DFS pushes neighbours without a visited check
triangle 0-1-2, bounded at 10 pops
DFS order: 0 2 1 2 1 2 1 2 1 2, expected 0 1 2 for 3 vertices
stopped by the bounded loop: true

Without a visited check the iterative DFS pushes the same vertices around a cycle forever. The program bounds the loop at ten pops on a triangle and the order repeats 0 2 1 2 1 2 1 2 1 2, where the correct preorder is 0 1 2. The visited array is what turns a walk into a traversal. The fix is to check it when a vertex is popped.

4. Distance Zero for Every Vertex

int main(void)
{
    unsigned char adjacency[VERTICES][VERTICES] = { { 0 } };
    int queue[QUEUE_CAPACITY];
    unsigned char visited[VERTICES] = { 0 };
    int distances[VERTICES];
    int head = 0;
    int tail = 0;
    int vertex;
    int unreachable = -1;

    add_edge(adjacency, 0, 1);
    add_edge(adjacency, 1, 2);
    add_edge(adjacency, 3, 4);

    printf("distance_zero_sentinel: distances start at 0 instead of -1\n");
    printf("%d vertices in two components, BFS from 0\n", VERTICES);

    /* The bug: every vertex starts at distance 0, so an unreached vertex looks
     * like the source itself. */
    for (vertex = 0; vertex < VERTICES; ++vertex)
        distances[vertex] = 0;
    visited[0] = 1;
    queue[tail++] = 0;
    while (head < tail) {
        int current = queue[head++];
        int next;
        for (next = 0; next < VERTICES; ++next) {
            if (adjacency[current][next] && !visited[next] &&
                tail < QUEUE_CAPACITY) {
                visited[next] = 1;
                distances[next] = distances[current] + 1;
                queue[tail++] = next;
            }
        }
    }

    printf("distances from 0:");
    for (vertex = 0; vertex < VERTICES; ++vertex)
        printf(" %d", distances[vertex]);
    printf("\n");

    for (vertex = 0; vertex < VERTICES; ++vertex) {
        if (!visited[vertex]) {
            unreachable = vertex;
            break;
        }
    }
    if (unreachable < 0) {
        fputs("no unreachable vertex: the graph changed\n", stderr);
        return EXIT_FAILURE;
    }
    printf("vertex %d: distance %d, expected -1 (unreachable)\n", unreachable,
           distances[unreachable]);
    return EXIT_SUCCESS;
}

Output:

distance_zero_sentinel: distances start at 0 instead of -1
5 vertices in two components, BFS from 0
distances from 0: 0 1 2 0 0
vertex 3: distance 0, expected -1 (unreachable)

Initializing distances to 0 instead of -1 makes every vertex look reachable at distance 0 until the BFS touches it. The graph has two components, and after the BFS from vertex 0 the distances read 0 1 2 0 0: vertices 3 and 4 were never visited and still report 0, where the correct answer is -1. The fix is the -1 sentinel, so an unreachable vertex can no longer pass for the source.

5. A Pointer Into a Grown Adjacency List

// dangling_list_pointer.cpp - DO NOT COPY. A reference into a
// std::vector<std::vector<int>> names a row object that lives inside the outer
// vector's buffer. Adding a vertex grows that buffer, moves every row and frees
// the old storage, so the reference dangles; reading through it is undefined
// behaviour and AddressSanitizer reports heap-use-after-free. Re-read the row
// after the growth (adjacency[0]), reserve the outer vector up front, or hold
// the row by value.
// Build: g++ -std=c++17 -Wall -Wextra -pedantic -g -fsanitize=address pitfalls/dangling_list_pointer.cpp -o dangling_list_pointer
#include <iostream>
#include <vector>

int main()
{
    // The adjacency lists of vertices 0 and 1, a vector of vectors.
    std::vector<std::vector<int>> adjacency(2);
    adjacency[0].push_back(1);
    adjacency[1].push_back(0);

    // The reference names the row object of vertex 0 inside the outer vector.
    const std::vector<int>& row_of_0 = adjacency[0];
    std::cout << "dangling_list_pointer: reference into an adjacency row across growth\n";
    std::cout << "row of 0 before growth: " << row_of_0.size() << " entries\n";

    // A vertex arrives: the outer vector reallocates, moves the row objects and
    // frees the buffer that held them. row_of_0 still names the old address.
    adjacency.emplace_back();
    adjacency[2].push_back(0);
    adjacency[0].push_back(2);
    std::cout << "vertices after growth: " << adjacency.size() << '\n';
    std::cout.flush();

    // AddressSanitizer stops at the first read of the freed row object.
    std::cout << "row of 0 after growth: " << row_of_0.size() << " entries\n";
    std::cout << "first neighbour of 0: " << row_of_0.front() << '\n';
    return 0;
}

Output:

AddressSanitizer: heap-use-after-free
READ of size 8 at pitfalls/dangling_list_pointer.cpp:33
8 bytes inside a 48-byte region freed at pitfalls/dangling_list_pointer.cpp:26
allocated at pitfalls/dangling_list_pointer.cpp:15
SUMMARY: AddressSanitizer: heap-use-after-free pitfalls/dangling_list_pointer.cpp:33 in main

A reference into a vector of vectors is a reference into the outer vector’s storage, not a handle that survives growth. Keeping a reference to one adjacency row while the outer vector grows reallocates that storage, and reading the reference afterwards is a use-after-free: AddressSanitizer reports a read of 8 bytes inside a freed 48-byte region. Reserve the outer vector, store an index instead of a reference, or read the row before the container can grow.

Key Takeaways

  • A graph stores relationships, with V vertices and E edges. The representation chooses between O(V²) memory with constant-time edge checks and O(V + E) memory with neighbor scans.
  • The adjacency matrix is best for dense graphs and edge queries, and the adjacency list for sparse graphs and traversal. At 5,000 vertices the list was 160 KB sparse against a 25 MB matrix, and 100 MB dense against the same matrix.
  • BFS uses a queue and gives shortest unweighted distances and connected components in O(V + E) with a list. A matrix makes the traversal O(V squared), which showed as 16 ms of cell checks against under a millisecond on the sparse graph.
  • DFS uses a stack, recursive or explicit, and the preorder and postorder it produces are the basis for cycle detection, topological sorting and component algorithms.
  • The recursive DFS goes 10,000 frames deep on a 10,000-vertex path and dies with SIGSEGV at 100,000 under a 1 MB stack. The iterative version swaps the call stack for a vector and completes the 100,000 vertices with an explicit stack that never held more than one.
  • Mark visited when enqueuing in BFS and when popping in DFS, and store an undirected edge in both directions. Those are the three mistakes the pitfalls below demonstrate.
  • None of these standard libraries ships a graph container. The adjacency list is a list of lists, and Boost Graph, JGraphT, NetworkX and QuikGraph are the library options when more is needed.

Conclusion

The graph article is a memory article in disguise. The traversal algorithms are short, the visited array is the only state they need, and the representation decides whether the same traversal takes a few milliseconds or checks millions of empty cells. The sparse graph’s list was 160 KB against a 25 MB matrix. The dense graph’s list was 100 MB against the same matrix, because at that density a one-byte cell is cheaper than two 4-byte list entries per edge. The recursive DFS adds the second lesson: the stack is a resource with a platform limit, and a 100,000-vertex path found it on a 1 MB stack.

In production code, use an adjacency list unless the graph is small and dense or the edge query is the hot path, and use the iterative traversal when the graph can be deep. The queue that BFS relies on has its own article, the types of data structures guide places the graph beside the linear and tree structures, the data structures hub lists the whole series, the Shortest Path article is the next step for weighted edges and uses the priority queue, and Kruskal’s algorithm uses the component count for spanning trees.

Source Code and Tests

All programs on this page are in the data-structures/graph-data-structure directory of the five MYCPLUS example repositories:

LanguageRepository directoryBuild status
Cmycplus/c-examples: data-structures/graph-data-structureC graph build status
C++mycplus/cpp-examples: data-structures/graph-data-structureC++ graph build status
Javamycplus/java-examples: data-structures/graph-data-structureJava graph build status
Pythonmycplus/python-examples: data-structures/graph-data-structurePython graph build status
C#mycplus/csharp-examples: data-structures/graph-data-structureC# graph build status

The C and C++ examples build and test with CMake:

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

Java runs with javac --release 17 -Xlint:all -Werror -d build src/*.java tests/*.java followed by java -ea -cp build GraphTest. Python runs with python -m unittest discover -s tests -v, and C# with dotnet build Graph.slnx -c Release followed by dotnet run --project tests/GraphTests -c Release --no-build.

What the builds check. Every demo’s stdout is compared byte for byte with tests/expected/ordered.txt. The tests compare the matrix and list membership, BFS distances and DFS order against reference implementations, components against a union-find model, and cover empty, disconnected and isolated cases plus a million-vertex path for the iterative DFS. The C and C++ workflows also run the tests, demo and pitfalls under AddressSanitizer and UndefinedBehaviorSanitizer. The builds do not check the timing figures: those belong to one machine and are captured with the article.

What I Verified

The example directories contain the test programs and the captured runs, and the table states which system ran each check.

CheckUbuntu 24.04 (WSL2)Windows 11 (MSVC)
Build and tests, C, GCC 13.3Pass (6 of 6 tests)Not applicable
Build and tests, C, Clang 18.1.3Pass (6 of 6 tests)Not applicable
Build and tests, C, MSVC 19.44 /W4 /WXNot applicablePass (6 of 6 tests)
Build and tests, C++, g++ 13.3Pass (2 of 2 tests)Not applicable
Build and tests, C++, clang++ 18.1.3Pass (2 of 2 tests)Not applicable
Build and tests, C++, MSVC 19.44 /W4 /WX /permissive-Not applicablePass (2 of 2 tests)
Java tests (JDK 21 on WSL, JDK 27 on Windows)Pass (tests and the demo diff)Pass (tests and the demo diff)
Python tests (3.12.3 on WSL, 3.14.6 on Windows), ruff and mypy –strictPass (19 tests and the demo diff)Pass (19 tests, ruff and mypy clean)
.NET build and tests (10.0.115 on WSL, 10.0.404 on Windows)Pass (tests and the demo diff)Pass (tests and the demo diff)
AddressSanitizer and UndefinedBehaviorSanitizer, C and C++ tests, demo and pitfallsPass (C 6 of 6, C++ 2 of 2)Not applicable
Five pitfalls, each caught by the check named in its sectionPass (4 C checks, 1 C++ check)Not applicable
Representation and depth experimentsRun on Ubuntu 24.04, output in the sections aboveNot run

Not covered: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, Java 17 and 25 locally (the CI matrix covers them), macOS, weighted graphs and Dijkstra (the Shortest Path article), and timings on any other machine.

Scroll to Top