A graph is the info construction you attain for when the relationships are the info. For five,000 vertices, the sparse graph within the experiments under shops its edges in an adjacency checklist of 160 KB, whereas the identical graph as an adjacency matrix prices 25 MB, most of it empty.
Make the graph dense and the comparability reverses: the checklist grows to 100 MB whereas the matrix stays at 25 MB. The illustration decides the reminiscence and the traversal price earlier than a single algorithm runs. And when a recursive DFS meets a 100,000-vertex path on a 1 MB stack, it crashes, whereas the iterative model walks the entire path with out rising the decision stack.
This information implements an undirected graph as each an adjacency matrix and an adjacency checklist in C, C++, Java, Python and C#. It measures each representations on sparse and dense graphs and walks them with breadth-first and depth-first search. None of those commonplace libraries ships a graph container, so the adjacency checklist is normally a listing of lists. Each program was constructed and examined on Ubuntu 24.04 underneath WSL2 and on Home windows 11 with MSVC, Java, Python and .NET. All 5 languages print the identical demo output byte for byte, and each output block under comes from an actual run.
What Is a Graph?
A graph is a set of vertices linked by edges, and it shops relationships that don’t have any pure order or hierarchy: who’s linked to whom, which web page hyperlinks to which, which metropolis has a street to which. The 2 widespread representations are the adjacency matrix, a V by V desk of edge flags, and the adjacency checklist, one checklist of neighbors per vertex.
A graph has two numbers that resolve every thing: V, the variety of vertices, and E, the variety of edges. An undirected graph shops every edge as soon as within the conceptual mannequin and twice in most representations, as a result of a vertex’s entry should level again. A directed graph shops every edge as soon as and the reverse edge could not exist. A weighted graph attaches a price to every edge, after which the traversal questions change from reachability to price, which is the place Dijkstra’s algorithm lives.
The 2 traversals reply totally different questions. Breadth-first search begins at a supply, visits each vertex at distance one, then distance two, and so forth, which supplies the shortest path in an unweighted graph and the linked elements.
Depth-first search follows one edge so far as it will possibly go earlier than backing up, which supplies preorder and postorder orderings, cycle detection, topological order for directed acyclic graphs and maze fixing. Each go to every vertex and every edge a continuing variety of instances, so each are O(V + E) with an adjacency checklist. With a matrix, discovering a vertex’s neighbors prices V per vertex, so traversal turns into O(V²) irrespective of how few edges there are. That’s the measured distinction on this article.
Illustration is a reminiscence determination as a lot as a pace determination. The matrix makes use of V² cells, which is ok at 100 vertices and not possible at 100,000. The checklist makes use of area proportional to E, which is tiny for a sparse graph and bigger than the matrix for a dense one if the per-entry overhead outweighs the saved zeros. The Shortest Path article is the place weighted graphs take over with Dijkstra, and Kruskal’s algorithm makes use of the connected-components query for spanning bushes, whereas this text covers the illustration, BFS and DFS.
How This Was Measured
| Setting | Worth |
|---|---|
| Date examined | December 1, 2026 |
| {Hardware} | Intel Core i7-8700K, 6 cores and 12 threads at 3.70 GHz, 32 GB RAM, Home windows 11 Schooling construct 26300 |
| Working system | Ubuntu 24.04.5 underneath WSL2, kernel 5.15.146.1-microsoft-standard-WSL2, glibc 2.39; Home windows 11 for the MSVC, Java and .NET builds |
| Compilers | GCC 13.3 and Clang 18.1.3 at -O2 and -O3 by CMake Launch; MSVC 19.44 at /W4 /WX |
| Language runtimes | OpenJDK 27.0.1.1 (the CI matrix covers 17, 21 and 25); CPython 3.14.6; .NET SDK 10.0.404 |
| Illustration experiment | 5,000 vertices: a sparse graph with 15,000 distinctive random edges and the whole dense graph with 12,497,500 edges |
| Depth experiment | Path graphs of 10,000 and 100,000 vertices; the 100,000 case runs the recursive DFS in a forked baby with a 1 MB stack restrict |
| What’s timed | Construct, BFS and DFS calls on the 2 representations; edge era is exterior the timed areas |
| Statistic | Single run for every measurement and illustration, milliseconds; allotted bytes counted structurally and verified in opposition to the allocations |
| Test | The matrix and the checklist should produce the identical BFS distance array for each graph |
No CPU pinning or frequency scaling management was used, and the host runs different software program, so timings are indicative for this machine and the ratios are the helpful half. All numbers come from one machine and one WSL2 occasion. The dense graph is full by building, so its edge rely is mounted at V(V – 1) / 2 fairly than random.
Three Representations and What They Value
The adjacency matrix is a V by V desk: matrix[u][v] is ready when the sting exists, and for an undirected graph the desk is symmetric, so the storage holds 2E set cells. Checking an edge is one array entry, and eradicating an edge is one write. Iterating a vertex’s neighbors scans the entire row, which prices V even when the vertex has one neighbor. The reminiscence is V² cells no matter E, which is the matrix’s energy and its weak point: at 100,000 vertices a byte per cell is 10 GB, so the illustration merely doesn’t match.
The adjacency checklist is one checklist per vertex, every holding that vertex’s neighbors. For an undirected graph each edge seems twice, so the storage is 2E entries plus V checklist headers. Checking an edge means looking one endpoint’s checklist, which prices the diploma, or its logarithm when the checklist is saved sorted as in these examples. Iterating the neighbors prices precisely the diploma, so traversal is O(V + E). The reminiscence grows with E, which is why giant sparse graphs use it.
The sting checklist, a flat array of pairs, is the third illustration: most cost-effective to construct and skim from a file, and worst for lookups, since discovering a vertex’s neighbors scans each edge.
| Operation | Adjacency matrix | Adjacency checklist | Edge checklist |
|---|---|---|---|
| Reminiscence | O(V²) | O(V + E) | O(E) |
| has_edge | O(1) | O(diploma) | O(E) |
| Neighbors of v | O(V) | O(diploma) | O(E) |
| BFS or DFS | O(V²) | O(V + E) | O(V + E) after conversion |
| Add edge | O(1) | O(1) amortized, O(diploma) when saved sorted as right here | O(1) amortized |
| Greatest for | Dense graphs, constant-time queries | Sparse graphs, traversal | Constructing and streaming |
The demo graph under makes use of seven vertices and 9 edges. Its matrix has 18 set cells as a result of every undirected edge seems twice, and its lists collectively maintain 18 entries for a similar cause. Each representations reply the identical reachability questions, and the traversals should agree on them.
BFS and DFS: Two Methods to Stroll the Similar Graph
Breadth-first search makes use of a queue. It marks the supply visited, enqueues it, and repeatedly dequeues a vertex and enqueues each unvisited neighbor, marking every when it’s enqueued. As a result of the queue serves vertices within the order they have been found, the search reaches each vertex at distance d earlier than any vertex at distance d + 1.
So the gap array it fills is the shortest-path distance in an unweighted graph and the visited set is precisely the supply’s linked part. Repeating the seek for each unvisited vertex counts the elements.
Depth-first search makes use of a stack: the decision stack within the recursive type, an express array within the iterative one. It marks the supply, then follows one edge so far as potential, backtracking solely when a vertex has no unvisited neighbor. The order wherein vertices are first found is the preorder, and the order wherein they end is the postorder. The 2 orderings are the premise for cycle detection, topological sorting and strongly linked elements.
The recursive type is the shortest code, however every stage of depth prices a stack body. A path graph of 100,000 vertices is 100,000 frames deep, which may exceed the stack: Home windows offers a thread 1 MB by default and Linux usually 8 MB. The iterative type swaps the decision stack for a vector that this system controls.
Each traversals want a visited marker. In BFS the marker should be set when a vertex is enqueued, not when it’s dequeued, or a vertex with a number of neighbors is enqueued a number of instances and the queue grows past V. In DFS the marker should be checked when a vertex is popped, or a cycle retains pushing it. The pitfalls part demonstrates each, plus the matrix that shops an undirected edge solely as soon as.
Graph Implementation in C
The C model retains each representations in a single construction: a byte matrix of V by V cells and a listing of adjacency arrays sized by vertex. The demo builds the seven-vertex graph, checks two edges by each representations, then runs BFS and DFS and counts elements. The BFS queue is an array of vertex ids with head and tail indexes, and the DFS stack is a plain array with a high index.
bool graph_add_edge(Graph *graph, int u, int v)
int graph_bfs(const Graph *graph, int supply, 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, supply))
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++] = supply;
whereas (head < tail) {
int present = queue[head++];
const AdjList *row = &graph->lists[current];
size_t index;
order[reached++] = present;
for (index = 0; index < row->measurement; ++index) {
int subsequent = row->ids[index];
if (!visited[next]) {
visited[next] = 1;
distances[next] = distances[current] + 1;
queue[tail++] = subsequent;
}
}
}
free(queue);
free(visited);
return reached;
}
int graph_dfs(const Graph *graph, int supply, 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, supply))
return -1;
visited = calloc((size_t)vertices, sizeof *visited);
if (visited == NULL)
return -1;
if (!stack_push(&stack, &stack_size, &stack_capacity, supply)) {
free(visited);
return -1;
}
whereas (stack_size > 0) {
int present = stack[--stack_size];
const AdjList *row;
size_t index;
if (visited[current])
proceed;
visited[current] = 1;
order[reached++] = present;
row = &graph->lists[current];
for (index = row->measurement; index > 0; --index) {
int subsequent = row->ids[index - 1];
if (!visited[next] &&
!stack_push(&stack, &stack_size, &stack_capacity, subsequent)) {
free(stack);
free(visited);
return -1;
}
}
}
free(stack);
free(visited);
return reached;
}
The BFS loop is the entire algorithm: dequeue a vertex, scan its neighbors, mark and enqueue every unvisited one, and set its distance to the mum or dad’s plus one. The DFS loop pushes neighbors in reverse id order so the smallest is popped subsequent, which reproduces the recursive preorder with out rising the decision stack. Each traversals ask the adjacency checklist for neighbors, in order that they run in O(V + E). The matrix is there for the constant-time edge question and for the measured comparability.
Output:
undirected graph: 7 vertices, 9 edges
adjacency matrix: 7 x 7, 18 ones
adjacency checklist: 7 lists, 18 entries
edge 1-3: matrix true, checklist true
edge 0-3: matrix false, checklist 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
elements: 1
Graph Implementation in C++
The C++ model is a category with a std::vector<std::vector<unsigned char>> matrix and a std::vector<std::vector<int>> adjacency checklist. The matrix makes use of one byte per cell as a result of std::vector<bool> packs bits behind proxy references, which complicates factor entry. BFS returns the go to order and a distance vector, DFS returns the preorder, and elements repeats the iterative DFS from each unvisited vertex.
inline Graph::BfsResult Graph::bfs(int supply) const
{
BfsResult outcome;
outcome.distance.assign(vertex_count_, -1);
if (!valid_vertex(supply))
return outcome;
std::queue<int> pending;
outcome.distance[static_cast<std::size_t>(source)] = 0;
outcome.order.push_back(supply);
pending.push(supply);
whereas (!pending.empty()) {
const int vertex = pending.entrance();
pending.pop();
const int distance =
outcome.distance[static_cast<std::size_t>(vertex)] + 1;
// The row is ascending, so the neighbours are enqueued in ascending id
// order and the go to order of every distance stage is ascending too.
for (const int neighbour : lists_[static_cast<std::size_t>(vertex)]) {
if (outcome.distance[static_cast<std::size_t>(neighbour)] != -1)
proceed;
outcome.distance[static_cast<std::size_t>(neighbour)] = distance;
outcome.order.push_back(neighbour);
pending.push(neighbour);
}
}
return outcome;
}
inline std::vector<int> Graph::dfs_preorder(
const std::vector<std::vector<int>>& adjacency, int supply)
static_cast<std::size_t>(supply) >= adjacency.measurement())
return order;
std::vector<unsigned char> visited(adjacency.measurement(), 0);
visit_preorder(adjacency, supply, visited, order);
return order;
inline void Graph::visit_preorder(
const std::vector<std::vector<int>>& adjacency,
int supply,
std::vector<unsigned char>& visited,
std::vector<int>& order)
{
std::vector<int> stack;
stack.push_back(supply);
whereas (!stack.empty()) {
const int vertex = stack.again();
stack.pop_back();
if (visited[static_cast<std::size_t>(vertex)] != 0)
proceed;
visited[static_cast<std::size_t>(vertex)] = 1;
order.push_back(vertex);
// Reverse iteration places the smallest neighbour on high of the stack, so
// it's 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 usual library has no graph container, and the usual reply is the adjacency checklist above. The Increase Graph Library supplies one, with generic algorithms and property maps, however it’s exterior, template-heavy, and out of scope for this text. The Increase Graph documentation is the place to start out when the challenge already is determined by Increase.
Graph Implementation in Java, Python and C#
The three variations comply with the identical design: a matrix for edge queries, a listing of lists for traversal, BFS with a queue and distances, iterative DFS with an express stack, and a elements loop. None of those languages ships a graph container in its commonplace library, so the checklist of lists is the default all over the place.
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 supply) {
checkVertex(supply);
Listing<Integer> order = new ArrayList<>();
int[] distances = new int[vertices];
Arrays.fill(distances, -1);
Deque<Integer> queue = new ArrayDeque<>();
distances[source] = 0; // the gap array doubles because the visited marker
queue.add(supply);
whereas (!queue.isEmpty()) {
int vertex = queue.take away();
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 Listing<Integer> depthFirstOrder(Listing<Listing<Integer>> adjacency, int supply) {
Listing<Integer> order = new ArrayList<>();
boolean[] visited = new boolean[adjacency.size()];
Deque<Integer> stack = new ArrayDeque<>();
stack.push(supply);
whereas (!stack.isEmpty()) {
int vertex = stack.pop();
if (visited[vertex]) {
proceed; // a cycle could have queued the vertex twice
}
visited[vertex] = true;
order.add(vertex);
Listing<Integer> neighbours = adjacency.get(vertex);
for (int index = neighbours.measurement() - 1; index >= 0; index--) {
stack.push(neighbours.get(index)); // reverse order: lowest id on high
}
}
return order;
}
Graph makes use of int[][] for the matrix and Listing<Listing<Integer>> for the adjacency lists, saved sorted. It exposes addEdge, hasEdgeMatrix, hasEdgeList, bfs (returning order and distances), dfs, elements and the counts. Absence from the matrix is 0, and the README paperwork the simple-graph guidelines. JGraphT is the Java library for graphs with actual algorithms: jgrapht.org has the total API and a gallery of examples.
Python
def add_edge(self, u: int, v: int) -> bool:
"""Add the undirected edge as soon as and report whether or not it was added.
A self-loop, a replica edge and a vertex id exterior the graph are
ignored: the decision studies False and adjustments 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, supply: int) -> tuple[list[int], checklist[int]]:
"""Return the breadth-first go to order and the distances from supply.
Each reachable vertex is visited as soon as, by non-decreasing distance and
with neighbours in ascending id order. The gap checklist holds -1 for
each vertex the supply can't attain. An out of vary supply returns
an empty order with each distance -1.
"""
distances = [-1] * self._vertex_count
if not self._valid(supply):
return [], distances
order: checklist[int] = []
distances[source] = 0
queue: deque[int] = deque([source])
whereas 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]], supply: int) -> checklist[int]:
"""Return the iterative depth-first preorder over sorted adjacency lists.
The stack begins with the supply. A popped vertex that's already visited
is skipped, in any other case it's marked and appended, and its unvisited
neighbours are pushed in reverse ascending id order so the smallest id is
popped first. The outcome equals the recursive preorder when each checklist is
sorted, and no name recurses, which is what makes a path of 1,000,000
vertices secure. That is the engine behind ``Graph.dfs``; it's public so
that the deep path take a look at can stroll adjacency lists alone, with out allocating
a V by V matrix.
"""
if not 0 <= supply < len(adjacency):
return []
visited = [False] * len(adjacency)
order: checklist[int] = []
stack = [source]
whereas stack:
vertex = stack.pop()
if visited[vertex]:
proceed
visited[vertex] = True
order.append(vertex)
for neighbour in reversed(adjacency[vertex]):
if not visited[neighbour]:
stack.append(neighbour)
return order
The Python class retains the matrix as a listing of lists of bool and the adjacency lists as a listing of lists of int. BFS makes use of collections.deque, and the DFS stack is a listing used with append and pop. Python’s commonplace library has no graph sort, and NetworkX is the standard library when the challenge wants greater than a listing of lists: networkx.org paperwork the info buildings and algorithms.
C#
public bool AddEdge(int u, int 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 supply)
{
ValidateVertex(supply, nameof(supply));
int[] distances = new int[VertexCount];
Array.Fill(distances, -1);
distances[source] = 0;
var order = new Listing<int>(VertexCount);
var queue = new Queue<int>();
queue.Enqueue(supply);
whereas (queue.Rely > 0)
{
int vertex = queue.Dequeue();
order.Add(vertex);
foreach (int neighbour in _adjacency[vertex])
{
if (distances[neighbour] >= 0)
proceed;
distances[neighbour] = distances[vertex] + 1;
queue.Enqueue(neighbour);
}
}
return (order.ToArray(), distances);
}
inner static int[] DfsOrder(Listing<Listing<int>> adjacency, int supply)
{
bool[] visited = new bool[adjacency.Count];
var order = new Listing<int>(adjacency.Rely);
var stack = new Stack<int>();
stack.Push(supply);
whereas (stack.Rely > 0)
{
int vertex = stack.Pop();
if (visited[vertex])
proceed;
visited[vertex] = true;
order.Add(vertex);
Listing<int> neighbours = adjacency[vertex];
for (int index = neighbours.Rely - 1; index >= 0; index--)
stack.Push(neighbours[index]);
}
return order.ToArray();
}
The C# class makes use of a byte[,] matrix, one byte per cell, and Listing<Listing<int>> for the adjacency lists. BFS makes use of Queue<int>, and Elements walks every new part with a Stack<int>. QuikGraph is the C# library when a graph sort and its algorithms are wanted: QuikGraph on GitHub paperwork the API.
Sparse and Dense: The Measured Reminiscence
The reminiscence experiment builds each representations of the identical two graphs at 5,000 vertices: a sparse graph with 15,000 distinctive random edges, and the whole graph with 12,497,500 edges. It studies the bytes every illustration allocates and instances the construct of every. The matrix is counted at one byte per cell, and the checklist, saved 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 supply, 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++] = supply;
whereas (head < tail) {
int present = queue[head++];
const unsigned char *row = &graph->matrix[(size_t)current * (size_t)VERTICES];
int subsequent;
for (subsequent = 0; subsequent < VERTICES; ++subsequent) {
if (row[next] && !visited[next]) {
visited[next] = 1;
distances[next] = distances[current] + 1;
queue[tail++] = subsequent;
}
}
}
}
/* BFS from supply over the checklist, with the identical mark-on-enqueue rule. */
static void bfs_list(const ListGraph *graph, int supply, 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++] = supply;
whereas (head < tail) {
int present = queue[head++];
size_t index = graph->offsets[current];
for (; index < graph->offsets[current + 1]; ++index) {
int subsequent = graph->neighbours[index];
if (!visited[next]) {
visited[next] = 1;
distances[next] = distances[current] + 1;
queue[tail++] = subsequent;
}
}
}
}
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 each graphs, as a result of V squared cells don’t care what number of edges exist. The sparse graph’s adjacency checklist is 160,008 bytes, 156 instances smaller, and the dense graph’s checklist is 100,020,008 bytes, 4 instances bigger than the matrix.
The crossover is arithmetic. The checklist pays 8 bytes per edge (two 4-byte neighbor ids) plus 40,008 bytes of offsets, so at this V it beats the matrix under about 3.1 million edges and loses above. The counts have been verified in opposition to the allocation formulation, and the 2 representations produced the identical BFS distance array. The matrix is a set V squared tax that’s low-cost when the graph is dense and ruinous when it isn’t. A bit-per-cell matrix would transfer the crossover right down to about 390,000 edges with out altering the form of the argument.
BFS and DFS on Each Representations
The identical experiment walks every graph with each representations: BFS from vertex 0 and iterative DFS from vertex 0, timed individually, and the 2 representations should produce the identical distance array. The reminiscence desk above already explains a lot of the timings.
The sparse graph is the place the matrix’s mounted tax exhibits. Its BFS and DFS took 16 ms every, whereas the checklist walked the identical 15,000 edges in underneath a millisecond, as a result of the matrix should verify all 25 million cells to seek out them.
The dense graph reverses the comparability. The matrix’s BFS took 13 ms in opposition to the checklist’s 23 ms, and each DFS runs took 19 ms. The checklist now holds 24,995,000 entries, two per edge, so it does the identical order of labor because the matrix’s 25 million cell checks, and the matrix reads its byte rows with higher locality than the checklist reads 4-byte ids. The zero entries imply underneath half a millisecond, not zero work. These are single runs, so the reminiscence desk and the O(V squared) in opposition to O(V + E) argument carry the comparability, and the timings present the path at this measurement.
Recursive DFS In opposition to a Lengthy Path
The depth experiment runs three walks on path graphs. The iterative DFS visits a 100,000-vertex path and studies the biggest the specific stack ever grew. The recursive DFS visits a ten,000-vertex path on the default stack and studies its deepest body. The recursive DFS on the 100,000-vertex path runs in a forked baby whose stack is restricted to 1 MB, so the crash is contained and the mum or dad can report the sign as an alternative 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 subsequent = neighbours[index];
if (!visited[next]) {
dfs_recursive(offsets, neighbours, subsequent, visited, depth + 1,
visited_count, max_depth);
}
}
}
/* Iterative DFS with the article's express stack: push neighbours in reverse
* ascending order, verify visited when a vertex is popped, and report the
* largest stack the run ever held. On this path just one entry is ever pending
* at a time, no matter N is. The stack has room for the entire neighbour array,
* which is probably the most a stack entry can ever be. */
static bool dfs_iterative(const size_t *offsets, const int *neighbours,
int vertices, int supply, 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)supply;
if (stack_size > *max_stack)
*max_stack = stack_size;
whereas (stack_size > 0) {
int present = (int)stack[--stack_size];
size_t index;
if (visited[current])
proceed;
visited[current] = 1;
(*visited_count)++;
for (index = offsets[current + 1]; index > offsets[current]; --index) {
int subsequent = neighbours[index - 1];
if (!visited[next]) {
stack[stack_size++] = (size_t)subsequent;
if (stack_size > *max_stack)
*max_stack = stack_size;
}
}
}
free(stack);
return true;
}
Output:
path graph, undirected
vertices technique stack_limit visited max_depth outcome
10000 recursive DFS default 10000 10000 full
100000 recursive DFS 1 MB - - crash (sign 11)
100000 iterative DFS default 100000 1 full
The recursive DFS on the ten,000-vertex path went 10,000 frames deep and accomplished on the default stack. The iterative model on 100,000 vertices visited each vertex, and its express stack by no means held multiple vertex as a result of a path provides just one unvisited neighbor at every step.
The recursive model on the 100,000-vertex path, given a 1 MB stack, died on SIGSEGV, sign 11. That could be a platform boundary, not an algorithmic one. Each recursion stage prices a name body, and a path graph is the worst case for depth. The specific stack isn’t free normally, as a result of a star graph could make it maintain V vertices, however it’s reminiscence this system can account for and measurement, not like the decision stack.
5 Methods a Graph Traversal Passes a Fast Take a look at and Nonetheless Fails
Every of those applications compiles cleanly with -Wall -Wextra -pedantic and prints one thing believable till the road under it. The primary 4 stay within the C repository’s pitfalls/ listing and the fifth within the C++ repository’s, and the workflows re-run every and assert the road or sanitizer abstract that exhibits the bug.
1. Visited When Dequeued As an alternative of Enqueued
int principal(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 dequeuedn");
printf("%d vertices, full graph, BFS from 0n", VERTICES);
queue[tail++] = 0; /* supply is enqueued, not but marked */
queued++;
whereas (head < tail) {
int present = queue[head++];
int subsequent;
if (visited[current])
proceed; /* the mark occurred right here, too late */
visited[current] = 1;
for (subsequent = 0; subsequent < VERTICES; ++subsequent) {
if (adjacency[current][next] && !visited[next] &&
tail < QUEUE_CAPACITY) {
queue[tail++] = subsequent; /* enqueued and not using a mark */
queued++;
}
}
}
printf("BFS from 0 queued %d entries for %d vertices, anticipated %dn",
queued, VERTICES, VERTICES);
return EXIT_SUCCESS;
}
Output:
bfs_mark_on_dequeue: visited is marked when a vertex is dequeued
4 vertices, full graph, BFS from 0
BFS from 0 queued 7 entries for 4 vertices, anticipated 4
Marking a vertex when it’s dequeued lets its neighbors enqueue it once more earlier than it’s processed. On the four-vertex full graph the queue processed seven entries for 4 vertices. The duplicate work grows with the variety of edges, and on a big dense graph the queue can maintain much more entries than there are vertices. The repair is one line: mark the vertex when it’s enqueued, not when it’s dequeued.
2. An Undirected Edge Saved in One Course
static int bfs_reachable(unsigned char matrix[VERTICES][VERTICES], int supply)
{
int queue[QUEUE_CAPACITY];
unsigned char visited[VERTICES] = { 0 };
int head = 0;
int tail = 0;
int reached = 0;
visited[source] = 1;
queue[tail++] = supply;
whereas (head < tail) {
int present = queue[head++];
int subsequent;
reached++;
for (subsequent = 0; subsequent < VERTICES; ++subsequent) {
if (matrix[current][next] && !visited[next] &&
tail < QUEUE_CAPACITY) {
visited[next] = 1;
queue[tail++] = subsequent;
}
}
}
return reached;
}
Output:
matrix_unsymmetric: add_edge writes solely matrix[u][v]
3 vertices, edges 0-2 and 1-2
BFS from 2 reached 1 of three vertices, anticipated 3; elements: 2, anticipated 1
An undirected edge should be written in each matrix cells. This program writes solely matrix[u][v], so a traversal that begins at v can’t see u. The BFS from vertex 2 reached one among three vertices as an alternative of three, and the part rely got here out two as an alternative of 1. A take a look at that solely checks an edge within the order it was added would by no means discover.
3. A DFS With No Visited Test
int principal(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 and not using a visited checkn");
printf("triangle 0-1-2, bounded at %d popsn", MAX_POPS);
stack[stack_size++] = 0;
whereas (stack_size > 0) {
int present;
int subsequent;
if (order_count >= MAX_POPS) {
bounded = true;
break;
}
present = stack[--stack_size];
order[order_count++] = present; /* no visited array exists */
for (subsequent = 0; subsequent < VERTICES; ++subsequent) {
if (adjacency[current][next] && stack_size < STACK_CAPACITY)
stack[stack_size++] = subsequent;
}
}
printf("DFS order:");
for (vertex = 0; vertex < order_count; ++vertex)
printf(" %d", order[vertex]);
printf(", anticipated 0 1 2 for %d verticesn", VERTICES);
printf("stopped by the bounded loop: %sn", bounded ? "true" : "false");
return EXIT_SUCCESS;
}
Output:
dfs_no_visited: iterative DFS pushes neighbours and not using a visited verify
triangle 0-1-2, bounded at 10 pops
DFS order: 0 2 1 2 1 2 1 2 1 2, anticipated 0 1 2 for 3 vertices
stopped by the bounded loop: true
With out a visited verify the iterative DFS pushes the identical vertices round a cycle eternally. This system bounds the loop at ten pops on a triangle and the order repeats 0 2 1 2 1 2 1 2 1 2, the place the proper preorder is 0 1 2. The visited array is what turns a stroll right into a traversal. The repair is to verify it when a vertex is popped.
4. Distance Zero for Each Vertex
int principal(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 begin at 0 as an alternative of -1n");
printf("%d vertices in two elements, BFS from 0n", VERTICES);
/* The bug: each vertex begins at distance 0, so an unreached vertex appears
* just like the supply itself. */
for (vertex = 0; vertex < VERTICES; ++vertex)
distances[vertex] = 0;
visited[0] = 1;
queue[tail++] = 0;
whereas (head < tail) {
int present = queue[head++];
int subsequent;
for (subsequent = 0; subsequent < VERTICES; ++subsequent) {
if (adjacency[current][next] && !visited[next] &&
tail < QUEUE_CAPACITY) {
visited[next] = 1;
distances[next] = distances[current] + 1;
queue[tail++] = subsequent;
}
}
}
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 changedn", stderr);
return EXIT_FAILURE;
}
printf("vertex %d: distance %d, anticipated -1 (unreachable)n", unreachable,
distances[unreachable]);
return EXIT_SUCCESS;
}
Output:
distance_zero_sentinel: distances begin at 0 as an alternative of -1
5 vertices in two elements, BFS from 0
distances from 0: 0 1 2 0 0
vertex 3: distance 0, anticipated -1 (unreachable)
Initializing distances to 0 as an alternative of -1 makes each vertex look reachable at distance 0 till the BFS touches it. The graph has two elements, and after the BFS from vertex 0 the distances learn 0 1 2 0 0: vertices 3 and 4 have been by no means visited and nonetheless report 0, the place the proper reply is -1. The repair is the -1 sentinel, so an unreachable vertex can not cross for the supply.
5. A Pointer Right into a Grown Adjacency Listing
// dangling_list_pointer.cpp - DO NOT COPY. A reference right into a
// std::vector<std::vector<int>> names a row object that lives contained in the outer
// vector's buffer. Including a vertex grows that buffer, strikes each row and frees
// the previous storage, so the reference dangles; studying by it's undefined
// behaviour and AddressSanitizer studies heap-use-after-free. Re-read the row
// after the expansion (adjacency[0]), reserve the outer vector up entrance, or maintain
// the row by worth.
// Construct: g++ -std=c++17 -Wall -Wextra -pedantic -g -fsanitize=tackle pitfalls/dangling_list_pointer.cpp -o dangling_list_pointer
#embrace <iostream>
#embrace <vector>
int principal()
{
// 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 contained in the outer vector.
const std::vector<int>& row_of_0 = adjacency[0];
std::cout << "dangling_list_pointer: reference into an adjacency row throughout growthn";
std::cout << "row of 0 earlier than progress: " << row_of_0.measurement() << " entriesn";
// A vertex arrives: the outer vector reallocates, strikes the row objects and
// frees the buffer that held them. row_of_0 nonetheless names the previous tackle.
adjacency.emplace_back();
adjacency[2].push_back(0);
adjacency[0].push_back(2);
std::cout << "vertices after progress: " << adjacency.measurement() << 'n';
std::cout.flush();
// AddressSanitizer stops on the first learn of the freed row object.
std::cout << "row of 0 after progress: " << row_of_0.measurement() << " entriesn";
std::cout << "first neighbour of 0: " << row_of_0.entrance() << 'n';
return 0;
}
Output:
AddressSanitizer: heap-use-after-free
READ of measurement 8 at pitfalls/dangling_list_pointer.cpp:33
8 bytes inside a 48-byte area freed at pitfalls/dangling_list_pointer.cpp:26
allotted at pitfalls/dangling_list_pointer.cpp:15
SUMMARY: AddressSanitizer: heap-use-after-free pitfalls/dangling_list_pointer.cpp:33 in principal
A reference right into a vector of vectors is a reference into the outer vector’s storage, not a deal with that survives progress. Preserving a reference to at least one adjacency row whereas the outer vector grows reallocates that storage, and studying the reference afterwards is a use-after-free: AddressSanitizer studies a learn of 8 bytes inside a freed 48-byte area. Reserve the outer vector, retailer an index as an alternative of a reference, or learn the row earlier than the container can develop.
Key Takeaways
- A graph shops relationships, with V vertices and E edges. The illustration chooses between O(V²) reminiscence with constant-time edge checks and O(V + E) reminiscence with neighbor scans.
- The adjacency matrix is finest for dense graphs and edge queries, and the adjacency checklist for sparse graphs and traversal. At 5,000 vertices the checklist was 160 KB sparse in opposition to a 25 MB matrix, and 100 MB dense in opposition to the identical matrix.
- BFS makes use of a queue and offers shortest unweighted distances and linked elements in O(V + E) with a listing. A matrix makes the traversal O(V squared), which confirmed as 16 ms of cell checks in opposition to underneath a millisecond on the sparse graph.
- DFS makes use of a stack, recursive or express, and the preorder and postorder it produces are the premise for cycle detection, topological sorting and part algorithms.
- The recursive DFS goes 10,000 frames deep on a ten,000-vertex path and dies with SIGSEGV at 100,000 underneath a 1 MB stack. The iterative model swaps the decision stack for a vector and completes the 100,000 vertices with an express stack that by no means held multiple.
- Mark visited when enqueuing in BFS and when popping in DFS, and retailer an undirected edge in each instructions. These are the three errors the pitfalls under exhibit.
- None of those commonplace libraries ships a graph container. The adjacency checklist is a listing of lists, and Increase Graph, JGraphT, NetworkX and QuikGraph are the library choices when extra is required.
Continuously Requested Questions
Conclusion
The graph article is a reminiscence article in disguise. The traversal algorithms are brief, the visited array is the one state they want, and the illustration decides whether or not the identical traversal takes a couple of milliseconds or checks thousands and thousands of empty cells. The sparse graph’s checklist was 160 KB in opposition to a 25 MB matrix. The dense graph’s checklist was 100 MB in opposition to the identical matrix, as a result of at that density a one-byte cell is cheaper than two 4-byte checklist entries per edge. The recursive DFS provides the second lesson: the stack is a useful resource with a platform restrict, and a 100,000-vertex path discovered it on a 1 MB stack.
In manufacturing code, use an adjacency checklist except the graph is small and dense or the sting question is the new path, and use the iterative traversal when the graph might be deep. The queue that BFS depends on has its personal article, the sorts of information buildings information locations the graph beside the linear and tree buildings, the information buildings hub lists the entire collection, the Shortest Path article is the subsequent step for weighted edges and makes use of the precedence queue, and Kruskal’s algorithm makes use of the part rely for spanning bushes.
Supply Code and Assessments
All applications on this web page are within the data-structures/graph-data-structure listing of the 5 MYCPLUS instance repositories:
The C and C++ examples construct and take a look at with CMake:
cmake -S . -B construct
cmake --build construct
ctest --test-dir construct --output-on-failure
Java runs with javac --release 17 -Xlint:all -Werror -d construct src/*.java exams/*.java adopted by java -ea -cp construct GraphTest. Python runs with python -m unittest uncover -s exams -v, and C# with dotnet construct Graph.slnx -c Launch adopted by dotnet run --project exams/GraphTests -c Launch --no-build.
What the builds verify. Each demo’s stdout is in contrast byte for byte with exams/anticipated/ordered.txt. The exams examine the matrix and checklist membership, BFS distances and DFS order in opposition to reference implementations, elements in opposition to a union-find mannequin, and canopy empty, disconnected and remoted instances plus a million-vertex path for the iterative DFS. The C and C++ workflows additionally run the exams, demo and pitfalls underneath AddressSanitizer and UndefinedBehaviorSanitizer. The builds don’t verify the timing figures: these belong to at least one machine and are captured with the article.
What I Verified
The instance directories comprise the take a look at applications and the captured runs, and the desk states which system ran every verify.
| Test | Ubuntu 24.04 (WSL2) | Home windows 11 (MSVC) |
|---|---|---|
| Construct and exams, C, GCC 13.3 | Cross (6 of 6 exams) | Not relevant |
| Construct and exams, C, Clang 18.1.3 | Cross (6 of 6 exams) | Not relevant |
Construct and exams, C, MSVC 19.44 /W4 /WX |
Not relevant | Cross (6 of 6 exams) |
| Construct and exams, C++, g++ 13.3 | Cross (2 of two exams) | Not relevant |
| Construct and exams, C++, clang++ 18.1.3 | Cross (2 of two exams) | Not relevant |
Construct and exams, C++, MSVC 19.44 /W4 /WX /permissive- |
Not relevant | Cross (2 of two exams) |
| Java exams (JDK 21 on WSL, JDK 27 on Home windows) | Cross (exams and the demo diff) | Cross (exams and the demo diff) |
| Python exams (3.12.3 on WSL, 3.14.6 on Home windows), ruff and mypy –strict | Cross (19 exams and the demo diff) | Cross (19 exams, ruff and mypy clear) |
| .NET construct and exams (10.0.115 on WSL, 10.0.404 on Home windows) | Cross (exams and the demo diff) | Cross (exams and the demo diff) |
| AddressSanitizer and UndefinedBehaviorSanitizer, C and C++ exams, demo and pitfalls | Cross (C 6 of 6, C++ 2 of two) | Not relevant |
| 5 pitfalls, every caught by the verify named in its part | Cross (4 C checks, 1 C++ verify) | Not relevant |
| Illustration and depth experiments | Run on Ubuntu 24.04, output within the sections above | Not run |
Not coated: 32-bit builds, compilers newer than GCC 13.3 and Clang 18.1.3, Java 17 and 25 regionally (the CI matrix covers them), macOS, weighted graphs and Dijkstra (the Shortest Path article), and timings on every other machine.

