LOGBOOK

HELP

Quiz Entry - updated: 2026.11.27

Why do DFS and BFS run in $O(n + m)$ time with an adjacency list, and what do they cost with an adjacency matrix?

Each vertex and each edge is labelled a constant number of times, and incidentEdges(v) is called once per vertex. With an adjacency list that call costs $O(\deg(v))$, and the degrees add up to $2m$, so the total is $O(n + m)$. With an adjacency matrix each call has to scan v's whole row of $n$ cells, which makes $O(n^2)$ however few edges there are.

The incidence lists of a six-vertex graph, 18 entries for 9 edges, next to its 6 by 6 adjacency matrix, all 36 cells of which a traversal reads

* A list traversal touches each edge twice, once from each end; a matrix traversal reads every cell. *

The bookkeeping:

  1. Initialisation: every vertex and edge is labelled UNEXPLORED once, $O(n + m)$.
  2. Per vertex: one visit, one label change to VISITED and one call of incidentEdges, $O(n)$ altogether plus the cost of those calls. BFS also appends each vertex to exactly one level, once.
  3. Per edge: examined from each of its two ends and labelled once, a constant amount of work.

With an adjacency list, incidentEdges(v) hands over v's incidence sequence of $\deg(v)$ entries, and $\sum_v \deg(v) = 2m$. In total that is $O(n + m)$, which is the best possible: any algorithm that must look at the whole graph has to read its $n$ vertices and $m$ edges. Linear time means that a graph twice the size takes about twice as long.

With an adjacency matrix the edges of v are found only by scanning its row of $n$ cells, so the traversal costs $n \cdot n = n^2$ even for a graph with hardly any edges. For a sparse graph with a million vertices and a million edges that is about 3 million steps with the list against $10^{12}$ cells with the matrix. The edge list structure is worse again: it finds a vertex's edges only by scanning all $m$ edges, $O(n \cdot m)$ in total.

From Quiz: ADS / Graph Traversals: Depth-First and Breadth-First Search | Updated: Nov 27, 2026