Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

Graphs, BFS & DFS

Adjacency lists, breadth-first layers and depth-first exploration.

Breadth-first and depth-first search are among the oldest graph algorithms and still the most used. Each visits every vertex and edge once, in O(n+m)O(n + m) time, yet they answer different questions: BFS measures distances layer by layer, while the moments at which DFS enters and leaves each vertex expose cycles, components and, in the Optimal lessons, the weak points of a network.

What you’ll learn

  • Choose between adjacency lists and an adjacency matrix from the cost of each operation, and build adjacency lists in O(n+m)O(n + m).
  • Implement BFS with a queue and prove that it computes fewest-edge distances in O(n+m)O(n + m) time.
  • Implement DFS recursively and with an explicit stack, state the parenthesis and white-path theorems, and classify edges as tree, back, forward or cross edges.
  • Count connected components, detect cycles, and prove that a graph is bipartite exactly when it has no odd cycle.
  • Recognize unweighted shortest paths, flood fills, multi-source distances and two-colorings in problem statements, and avoid the classic traversal bugs.

Storing a graph

Throughout, G=(V,E)G = (V, E) has n=∣V∣n = \abs{V} vertices and m=∣E∣m = \abs{E} edges, and vertices are numbered 0,…,n−10, \dots, n - 1. The degree deg⁡(v)\deg(v) of a vertex is the number of edges at vv. Every edge has two ends, so

∑v∈Vdeg⁡(v)=2m,\sum_{v \in V} \deg(v) = 2m,

the handshake lemma. In a directed graph the in-degrees sum to mm, and so do the out-degrees.

OperationAdjacency listsAdjacency matrixEdge list
MemoryΘ(n+m)\Theta(n + m)Θ(n2)\Theta(n^2)Θ(m)\Theta(m)
Is uvuv an edge?O(deg⁡u)O(\deg u), or O(1)O(1) expected with hash setsO(1)O(1)O(m)O(m)
List the neighbors of uuΘ(deg⁡u)\Theta(\deg u)Θ(n)\Theta(n)O(m)O(m)
A whole BFS or DFSΘ(n+m)\Theta(n + m)Θ(n2)\Theta(n^2)convert to lists first, O(n+m)O(n + m)
Lists win on sparse graphs, the usual case: road networks, social networks, and contest inputs with mm up to a few times 10510^5. A matrix suits dense graphs with nn up to a few thousand and algorithms that read every pair anyway, such as Floyd–Warshall. Inputs, and Kruskal's algorithm, use edge lists.
python
def read_graph(n, edge_pairs, directed=False):
    """Adjacency lists for vertices 0..n-1 (subtract 1 first if the input counts from 1)."""
    adj = [[] for _ in range(n)]
    for u, v in edge_pairs:
        adj[u].append(v)
        if not directed:
            adj[v].append(u)          # an undirected edge is stored at both ends
    return adj

One pass over the edges: O(n+m)O(n + m) time, and exactly 2m2m list entries for an undirected graph. In C++ the same structure is a vector<vector<int>>; for very large graphs, one array of all neighbors plus an array of per-vertex offsets (the compressed sparse row format) is faster still.

Think first A graph has n=105n = 10^5 vertices and m=2⋅105m = 2 \cdot 10^5 edges. Roughly how much memory does each representation take?

Adjacency lists hold 2m=4⋅1052m = 4 \cdot 10^5 entries plus nn list headers: about 5⋅1055 \cdot 10^5 integers, around 2 MB at 4 bytes each. A matrix has n2=1010n^2 = 10^{10} cells: 1.25 GB even packed as bits, and 10 GB as bytes, almost all of them zero.

Breadth-first search and the layer invariant

Write δ(s,v)\delta(s, v) for the fewest edges on a path from ss to vv (∞\infty if there is none). BFS from ss discovers the vertices in order of δ(s,v)\delta(s, v). It keeps the discovered vertices in a first-in, first-out queue, and gives each one its distance and its parent, the vertex it was discovered from:

python
from collections import deque

def bfs(adj, s):
    """Fewest-edge distances from s (-1 = unreachable) and the BFS tree."""
    dist = [-1] * len(adj)
    parent = [-1] * len(adj)
    dist[s] = 0
    queue = deque([s])
    while queue:
        u = queue.popleft()
        for v in adj[u]:
            if dist[v] == -1:              # mark when enqueued, not when dequeued
                dist[v] = dist[u] + 1
                parent[v] = u
                queue.append(v)
    return dist, parent

Each vertex enters the queue at most once, and each adjacency list is scanned once, when its vertex leaves the queue: O(n+m)O(n + m) time and O(n)O(n) extra memory. Following parent from vv back to ss gives a shortest path, so the parent edges form a BFS tree.

DerivationProof
  1. dist[v] ≥ δ(s,v)for every discovered v\text{dist}[v] \ \ge\ \delta(s, v) \quad\text{for every discovered } v

    No underestimates. Every value dist[v]=dist[u]+1\text{dist}[v] = \text{dist}[u] + 1 is assigned along an edge uvuv, so by induction it is the length of a real path from ss, the tree path:

  2. dist[v1]≤dist[v2]≤⋯≤dist[vr]≤dist[v1]+1\text{dist}[v_1] \le \text{dist}[v_2] \le \cdots \le \text{dist}[v_r] \le \text{dist}[v_1] + 1

    The queue is sorted and spans at most two values. Let the queue hold v1,…,vrv_1, \dots, v_r from front to back. A dequeue only shortens the list. An enqueue appends dist[u]+1\text{dist}[u] + 1 for the vertex uu just dequeued, and uu was the old front, so dist[u]≤dist[v1]\text{dist}[u] \le \text{dist}[v_1] and dist[vr]≤dist[u]+1\text{dist}[v_r] \le \text{dist}[u] + 1. Both inequalities below survive every operation:

  3. u dequeued before v ⟹ dist[u]≤dist[v]u \text{ dequeued before } v \ \Longrightarrow\ \text{dist}[u] \le \text{dist}[v]

    Distances are handed out in order. The queue is sorted and only grows at the back, so vertices are enqueued, and dequeued, in nondecreasing order of dist\text{dist}:

  4. dist[v] ≤ dist[u]+1 = k,a contradiction.\text{dist}[v] \ \le\ \text{dist}[u] + 1 \ =\ k,\quad\text{a contradiction.}

    No overestimates. Suppose some vv ends with dist[v]>δ(s,v)=k\text{dist}[v] > \delta(s, v) = k; take such a vv with kk smallest, so k≥1k \ge 1. Its predecessor uu on a shortest path has δ(s,u)=k−1\delta(s, u) = k - 1, hence dist[u]=k−1\text{dist}[u] = k - 1. When uu is dequeued, either vv is undiscovered and gets dist[u]+1=k\text{dist}[u] + 1 = k, or it was discovered earlier and is still in the queue behind uu or already dequeued; then steps 2 and 3 give

Predict before you look

BFS starts in the top-left corner of a 10×1010 \times 10 grid with no walls, where each cell is joined to the cells above, below, left and right of it. What is the largest distance it assigns?

Show the answer

18

On an open grid, δ\delta is the Manhattan distance: rows apart plus columns apart. The far corner is 9 rows and 9 columns away, so its distance is 9+9=189 + 9 = 18, not 20. In general an N×NN \times N grid has largest distance 2(N−1)2(N - 1): 1,998 on a 1000×10001000 \times 1000 grid.

Depth-first search and its clock

DFS goes as deep as it can before backing up. The recursive version is short: mark uu, then recurse on every neighbor of uu that is still unmarked. Started from every unmarked vertex in turn, it builds a depth-first forest.

One clock, advanced at every event, stamps two times on each vertex: the discovery time d[u]d[u], when uu is first reached and turns gray, and the finishing time f[u]f[u], when every edge out of uu has been explored and it turns black. Undiscovered vertices are white.

python
def dfs_times(adj):
    """Discovery and finishing times of a DFS over the whole graph, without recursion."""
    n = len(adj)
    d, f = [0] * n, [0] * n
    clock = 0
    for root in range(n):
        if d[root]:
            continue
        clock += 1
        d[root] = clock
        stack = [(root, 0)]                 # (vertex, index of its next neighbor)
        while stack:
            u, i = stack[-1]
            if i < len(adj[u]):
                stack[-1] = (u, i + 1)
                v = adj[u][i]
                if not d[v]:                # white: (u, v) is a tree edge
                    clock += 1
                    d[v] = clock
                    stack.append((v, 0))
            else:                           # every neighbor scanned: u finishes
                stack.pop()
                clock += 1
                f[u] = clock
    return d, f

Recursion is the natural way to write DFS, but a path of 10510^5 vertices exceeds Python's default recursion limit of 1000 and can overflow a C++ call stack too. This version keeps its own stack of (vertex, next neighbor) pairs and reproduces the recursive DFS exactly, times included, in O(n+m)O(n + m) time.

The parenthesis theorem is the stack discipline in disguise: a vertex discovered while uu is gray is pushed above uu and popped before it. The white-path theorem takes a short argument along the path (CLRS proves both). Together they classify each edge (u,v)(u, v) by the color of vv at the moment DFS first explores the edge from uu:

Color of vvEdge typeTimesMeaning
whitetree edged[u]<d[v]<f[v]<f[u]d[u] < d[v] < f[v] < f[u]vv is discovered from uu
grayback edged[v]<d[u]<f[u]<f[v]d[v] < d[u] < f[u] < f[v]vv is an ancestor still on the stack: the edge closes a cycle
black, d[u]<d[v]d[u] < d[v]forward edged[u]<d[v]<f[v]<f[u]d[u] < d[v] < f[v] < f[u]vv is a descendant that has already finished
black, d[v]<d[u]d[v] < d[u]cross edged[v]<f[v]<d[u]<f[u]d[v] < f[v] < d[u] < f[u]vv finished in another branch before uu was discovered
Forward and cross edges occur only in directed graphs.
Check your understanding

During a DFS of a directed graph, the edge (u,v)(u, v) is explored while uu is gray and vv is black with d[v]>d[u]d[v] > d[u]. What kind of edge is it?

  1. A tree edge
  2. A back edge
  3. A cross edge
  4. A forward edge
Show the answer

D. A forward edge

vv was discovered after uu and has finished while uu is still open, so its interval nests inside uu's: vv is a descendant of uu, reached earlier along another path. An edge to a finished descendant is a forward edge. On the DAG above, A→DA \to D is one: D (3/6) finished inside A's interval (1/12) before A explored that edge.

What one traversal tells you

Most uses of BFS and DFS are one traversal plus a little bookkeeping:

  • Connected components. Start a search from every vertex not yet visited and number the searches. Each search marks exactly one component, all in O(n+m)O(n + m).
  • Cycles in undirected graphs. The graph has a cycle exactly when DFS finds a back edge: an edge to an already visited vertex, other than the edge it arrived by. Compare edge ids rather than the parent vertex, or two parallel edges between the same pair are missed.
  • Cycles in directed graphs. A visited vertex proves nothing: only an edge into a gray vertex closes a cycle, as the lesson on DAGs proves.
  • Flood fill. On a grid, cells are vertices and neighboring open cells are joined. One search from each unvisited cell counts the regions and measures their sizes.
DerivationProof
  1. side(vi)≡side(v0)+i(mod2)⟹k is even\text{side}(v_i) \equiv \text{side}(v_0) + i \pmod 2 \quad\Longrightarrow\quad k \text{ is even}

    An odd cycle cannot be two-colored. Walking around a cycle v0,v1,…,vk=v0v_0, v_1, \dots, v_k = v_0, every edge switches sides, so returning to the starting side forces an even length:

  2. side(u)=side(v)⟹δ(s,u)=δ(s,v)=k\text{side}(u) = \text{side}(v) \quad\Longrightarrow\quad \delta(s, u) = \delta(s, v) = k

    Otherwise, color by the parity of the distance. Run BFS from one vertex ss in each component and put vv on side δ(s,v) mod 2\delta(s, v) \bmod 2. In an undirected graph every edge uvuv has ∣δ(s,u)−δ(s,v)∣≤1\abs{\delta(s, u) - \delta(s, v)} \le 1, so an edge inside one side joins two vertices of the same layer:

  3. (k−j)+(k−j)+1  =  2(k−j)+1,which is odd.(k - j) + (k - j) + 1 \;=\; 2(k - j) + 1,\quad\text{which is odd.}

    Such an edge closes an odd cycle. Follow the BFS-tree paths from uu and from vv up to their lowest common ancestor aa, at depth j<kj < k. The two paths share only aa, and with the edge uvuv they form a cycle of length

  4. So if the graph has no odd cycle, no edge lies inside a side and the parity coloring is a valid two-coloring; and if some edge does lie inside a side, BFS has found an odd cycle.

python
from collections import deque

def two_color(adj):
    """Side 0 or 1 for every vertex, or None if an edge joins two vertices of one side."""
    side = [-1] * len(adj)
    for s in range(len(adj)):
        if side[s] != -1:
            continue
        side[s] = 0
        queue = deque([s])
        while queue:
            u = queue.popleft()
            for v in adj[u]:
                if side[v] == -1:
                    side[v] = 1 - side[u]
                    queue.append(v)
                elif side[v] == side[u]:
                    return None             # an odd cycle exists
    return side

Two-coloring by BFS, restarted in every component: O(n+m)O(n + m). To report the odd cycle itself, keep the BFS parents and walk up from both ends of the offending edge to their lowest common ancestor, as in the proof.

Recognizing it

Signals. "Fewest moves", "minimum number of steps" or "shortest path" on a graph or grid where every move costs the same; "how many regions", "is everything connected", "can X reach Y"; "split into two groups so that every conflict crosses"; "distance to the nearest". Grids of up to about 10610^6 cells, or n+mn + m up to a few million, call for one linear pass.

Problem (in our words)Key ideaTime
Fewest knight moves between two squares of an N×NN \times N boardBFS on the implicit graph of squares; each square has at most 8 neighborsO(N2)O(N^2)
Count the islands in a grid of land and waterA flood fill (BFS or DFS) from every unvisited land cell; the number of fills is the answerO(RC)O(RC)
For every cell, the distance to the nearest exit; or how long until every orange in a crate has rottedMulti-source BFS: every source enters the queue at distance 0O(RC)O(RC), not one BFS per source
Split people into two teams so that every pair of rivals is separatedTwo-coloring; impossible exactly when the rivalries contain an odd cycleO(n+m)O(n + m)
Fewest one-letter changes turning one dictionary word into anotherBFS on an implicit graph of words: try every one-letter change and keep those in the dictionaryO(N⋅L⋅26)O(N \cdot L \cdot 26) lookups for NN words of length LL
Classic interview and contest problems. The third row is the multi-source trick: one BFS with kk sources costs as much as one BFS, not kk of them.

Common bugs.

  • Marking a vertex when it is dequeued instead of when it is enqueued: it can then enter the queue once per edge into it, and code that sets the distance at push time overwrites a correct value. On the 5-cycle with edges sasa, avav, vcvc, cbcb, bsbs, BFS from ss (neighbors in alphabetical order) rewrites dist[c]\text{dist}[c] from 2 to 3 when it dequeues vv.
  • Recursion depth: a path-shaped input of 10510^5 vertices breaks a recursive DFS in Python and can overflow a C++ stack. Use an explicit stack.
  • 1-indexed input stored in 0-indexed arrays, or an undirected edge added in one direction only.
  • Grid code that indexes before checking bounds, or forgets to reset visited between test cases.
  • A separate BFS from each of kk sources when one multi-source BFS would do.
cpp
#include <iostream>
#include <queue>
#include <string>
#include <utility>
#include <vector>
using namespace std;

int main() {
    int R, C;
    cin >> R >> C;
    vector<string> g(R);                       // '#' wall, '.' open, 'X' a source
    for (auto& row : g) cin >> row;
    vector<vector<int>> dist(R, vector<int>(C, -1));
    queue<pair<int, int>> q;
    for (int r = 0; r < R; r++)
        for (int c = 0; c < C; c++)
            if (g[r][c] == 'X') { dist[r][c] = 0; q.push({r, c}); }   // all sources at distance 0
    const int dr[4] = {-1, 0, 1, 0}, dc[4] = {0, 1, 0, -1};
    while (!q.empty()) {
        auto [r, c] = q.front();
        q.pop();
        for (int k = 0; k < 4; k++) {
            int nr = r + dr[k], nc = c + dc[k];
            if (nr < 0 || nr >= R || nc < 0 || nc >= C) continue;    // off the grid
            if (g[nr][nc] == '#' || dist[nr][nc] != -1) continue;     // wall, or reached already
            dist[nr][nc] = dist[r][c] + 1;
            q.push({nr, nc});
        }
    }
    for (int r = 0; r < R; r++)
        for (int c = 0; c < C; c++) cout << dist[r][c] << (c + 1 < C ? ' ' : '\n');
}

The contest idiom for grids: direction arrays, bounds checked before indexing, and every source pushed at distance 0. Each open cell gets the number of steps to its nearest source; walls and unreachable cells keep −1-1. Structured bindings need C++17.

Check your understanding

A 1000×10001000 \times 1000 grid map marks some cells as fire stations. For every cell, report how many steps (up, down, left or right, avoiding walls) separate it from the nearest fire station, within a second. Which approach fits?

  1. BFS from every cell, stopping at the first fire station it reaches
  2. One BFS that starts with every fire station in the queue at distance 0
  3. Dijkstra's algorithm from each fire station in turn
  4. DFS from each fire station, keeping the smallest depth seen at every cell
Show the answer

B. One BFS that starts with every fire station in the queue at distance 0

Joining a virtual super-source to every station turns "nearest station" into an ordinary BFS from one vertex, and putting all the stations in the queue at distance 0 does exactly that. One pass over 10610^6 cells costs a few million operations.

Key takeaways

  • Adjacency lists take Θ(n+m)\Theta(n + m) memory and make BFS and DFS run in O(n+m)O(n + m); with an adjacency matrix both take Θ(n2)\Theta(n^2).
  • BFS's FIFO queue stays sorted by distance and spans two consecutive values, which proves that dist[v]=δ(s,v)\text{dist}[v] = \delta(s, v) and that BFS-tree paths are shortest paths.
  • DFS stamps discovery and finishing times whose intervals nest (the parenthesis theorem); edges are tree, back, forward or cross edges, and an undirected graph has only tree and back edges.
  • One traversal counts components, finds cycles (back edges; in directed graphs, edges into gray vertices) and two-colors a graph, which succeeds exactly when there is no odd cycle.
  • Mark vertices when you enqueue them, avoid deep recursion, and use one multi-source BFS for "distance to the nearest".

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

BFS runs on a connected graph with nn vertices and mm edges stored as an adjacency matrix. What is its running time?

  1. Θ(n+m)\Theta(n + m)
  2. Θ(mlog⁡n)\Theta(m \log n)
  3. Θ(n2)\Theta(n^2)
  4. Θ(nm)\Theta(nm)
Show the answer

C. Θ(n2)\Theta(n^2)

Each dequeued vertex finds its neighbors by scanning its whole row of nn cells, and all nn vertices are dequeued: Θ(n2)\Theta(n^2), however few edges the graph has. That is optimal only for dense graphs, where m=Θ(n2)m = \Theta(n^2) anyway.

Question 2

In a depth-first search, d[u]=3d[u] = 3, f[u]=10f[u] = 10 and d[v]=5d[v] = 5. Which value of f[v]f[v] is possible?

  1. 44
  2. 88
  3. 1010
  4. 1111
Show the answer

B. 88

vv is discovered inside uu's interval, so by the parenthesis theorem vv is a descendant of uu and its interval nests inside [3,10][3, 10]: 5<f[v]<105 < f[v] < 10. Only 88 fits.

Question 3

BFS two-coloring finds an edge uvuv whose ends are on the same side. What does that prove?

  1. The graph has an odd cycle, so no two-coloring exists
  2. The coloring started from an unlucky vertex; another start might succeed
  3. The graph is not connected
  4. The edge uvuv is a bridge
Show the answer

A. The graph has an odd cycle, so no two-coloring exists

Same side means uu and vv lie in the same BFS layer kk. Their tree paths up to their lowest common ancestor, at some depth j<kj < k, together with uvuv form a cycle of length 2(k−j)+12(k - j) + 1, and no two-coloring survives an odd cycle, wherever it starts.

Question 4

A BFS marks a vertex visited only when it dequeues it, sets dist[v] = dist[u] + 1 each time it enqueues a not-yet-visited v, and skips dequeued vertices that are already visited. What goes wrong?

  1. Nothing: each vertex is still first dequeued at its true distance
  2. It loops forever on graphs with cycles
  3. It never reaches some reachable vertices
  4. A vertex waiting in the queue can have its distance overwritten by a larger one, and the queue can receive Θ(m)\Theta(m) entries
Show the answer

D. A vertex waiting in the queue can have its distance overwritten by a larger one, and the queue can receive Θ(m)\Theta(m) entries

A vertex stays unvisited while it waits in the queue, so every neighbor dequeued in the meantime pushes it again and rewrites its distance. On the 5-cycle with edges sasa, avav, vcvc, cbcb, bsbs (neighbors in alphabetical order), dequeuing vv rewrites dist[c]\text{dist}[c] from 2 to 3. On a complete graph with 50 vertices the queue receives 1,226 entries instead of 50. Marking at enqueue time fixes both.

Question 5

Why can a depth-first search of an undirected graph never produce a cross edge?

  1. Because undirected graphs have no cycles
  2. Because a neighbor vv that is still white when uu is discovered becomes uu's descendant, so every edge joins an ancestor and a descendant
  3. Because DFS visits the neighbors in sorted order
  4. Because every vertex finishes before its neighbors are discovered
Show the answer

B. Because a neighbor vv that is still white when uu is discovered becomes uu's descendant, so every edge joins an ancestor and a descendant

Take an edge uvuv with d[u]<d[v]d[u] < d[v]. At time d[u]d[u], vv is white and adjacent to uu, so by the white-path theorem it becomes a descendant of uu. Edges between an ancestor and a descendant are tree or back edges; a cross edge would need its ends in different branches.

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 20, "Elementary Graph Algorithms".
  • J. Kleinberg & É. Tardos, Algorithm Design (Addison-Wesley, 2005), chapter 3, "Graphs".
  • R. E. Tarjan, "Depth-first search and linear graph algorithms," SIAM Journal on Computing 1(2) (1972), 146–160.
  • E. F. Moore, "The shortest path through a maze," Proceedings of the International Symposium on the Theory of Switching (Harvard University Press, 1959), 285–292.