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 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 .
- Implement BFS with a queue and prove that it computes fewest-edge distances in 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, has vertices and edges, and vertices are numbered . The degree of a vertex is the number of edges at . Every edge has two ends, so
the handshake lemma. In a directed graph the in-degrees sum to , and so do the out-degrees.
| Operation | Adjacency lists | Adjacency matrix | Edge list |
|---|---|---|---|
| Memory | |||
| Is an edge? | , or expected with hash sets | ||
| List the neighbors of | |||
| A whole BFS or DFS | convert to lists first, |
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 adjOne pass over the edges: time, and exactly 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 vertices and edges. Roughly how much memory does each representation take?
Adjacency lists hold entries plus list headers: about integers, around 2 MB at 4 bytes each. A matrix has 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 for the fewest edges on a path from to ( if there is none). BFS from discovers the vertices in order of . 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:
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, parentEach vertex enters the queue at most once, and each adjacency list is scanned once, when its vertex leaves the queue: time and extra memory. Following parent from back to gives a shortest path, so the parent edges form a BFS tree.
No underestimates. Every value is assigned along an edge , so by induction it is the length of a real path from , the tree path:
The queue is sorted and spans at most two values. Let the queue hold from front to back. A dequeue only shortens the list. An enqueue appends for the vertex just dequeued, and was the old front, so and . Both inequalities below survive every operation:
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 :
No overestimates. Suppose some ends with ; take such a with smallest, so . Its predecessor on a shortest path has , hence . When is dequeued, either is undiscovered and gets , or it was discovered earlier and is still in the queue behind or already dequeued; then steps 2 and 3 give
BFS starts in the top-left corner of a 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, is the Manhattan distance: rows apart plus columns apart. The far corner is 9 rows and 9 columns away, so its distance is , not 20. In general an grid has largest distance : 1,998 on a grid.
Depth-first search and its clock
DFS goes as deep as it can before backing up. The recursive version is short: mark , then recurse on every neighbor of 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 , when is first reached and turns gray, and the finishing time , when every edge out of has been explored and it turns black. Undiscovered vertices are white.
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, fRecursion is the natural way to write DFS, but a path of 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 time.
The parenthesis theorem is the stack discipline in disguise: a vertex discovered while is gray is pushed above and popped before it. The white-path theorem takes a short argument along the path (CLRS proves both). Together they classify each edge by the color of at the moment DFS first explores the edge from :
| Color of | Edge type | Times | Meaning |
|---|---|---|---|
| white | tree edge | is discovered from | |
| gray | back edge | is an ancestor still on the stack: the edge closes a cycle | |
| black, | forward edge | is a descendant that has already finished | |
| black, | cross edge | finished in another branch before was discovered |
During a DFS of a directed graph, the edge is explored while is gray and is black with . What kind of edge is it?
- A tree edge
- A back edge
- A cross edge
- A forward edge
Show the answer
D. A forward edge
was discovered after and has finished while is still open, so its interval nests inside 's: is a descendant of , reached earlier along another path. An edge to a finished descendant is a forward edge. On the DAG above, 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 .
- 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.
An odd cycle cannot be two-colored. Walking around a cycle , every edge switches sides, so returning to the starting side forces an even length:
Otherwise, color by the parity of the distance. Run BFS from one vertex in each component and put on side . In an undirected graph every edge has , so an edge inside one side joins two vertices of the same layer:
Such an edge closes an odd cycle. Follow the BFS-tree paths from and from up to their lowest common ancestor , at depth . The two paths share only , and with the edge they form a cycle of length
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.
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 sideTwo-coloring by BFS, restarted in every component: . 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 cells, or up to a few million, call for one linear pass.
| Problem (in our words) | Key idea | Time |
|---|---|---|
| Fewest knight moves between two squares of an board | BFS on the implicit graph of squares; each square has at most 8 neighbors | |
| Count the islands in a grid of land and water | A flood fill (BFS or DFS) from every unvisited land cell; the number of fills is the answer | |
| For every cell, the distance to the nearest exit; or how long until every orange in a crate has rotted | Multi-source BFS: every source enters the queue at distance 0 | , not one BFS per source |
| Split people into two teams so that every pair of rivals is separated | Two-coloring; impossible exactly when the rivalries contain an odd cycle | |
| Fewest one-letter changes turning one dictionary word into another | BFS on an implicit graph of words: try every one-letter change and keep those in the dictionary | lookups for words of length |
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 , , , , , BFS from (neighbors in alphabetical order) rewrites from 2 to 3 when it dequeues .
- Recursion depth: a path-shaped input of 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
visitedbetween test cases. - A separate BFS from each of sources when one multi-source BFS would do.
#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 . Structured bindings need C++17.
A 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?
- BFS from every cell, stopping at the first fire station it reaches
- One BFS that starts with every fire station in the queue at distance 0
- Dijkstra's algorithm from each fire station in turn
- 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 cells costs a few million operations.
Key takeaways
- Adjacency lists take memory and make BFS and DFS run in ; with an adjacency matrix both take .
- BFS's FIFO queue stays sorted by distance and spans two consecutive values, which proves that 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.
BFS runs on a connected graph with vertices and edges stored as an adjacency matrix. What is its running time?
Show the answer
C.
Each dequeued vertex finds its neighbors by scanning its whole row of cells, and all vertices are dequeued: , however few edges the graph has. That is optimal only for dense graphs, where anyway.
In a depth-first search, , and . Which value of is possible?
Show the answer
B.
is discovered inside 's interval, so by the parenthesis theorem is a descendant of and its interval nests inside : . Only fits.
BFS two-coloring finds an edge whose ends are on the same side. What does that prove?
- The graph has an odd cycle, so no two-coloring exists
- The coloring started from an unlucky vertex; another start might succeed
- The graph is not connected
- The edge is a bridge
Show the answer
A. The graph has an odd cycle, so no two-coloring exists
Same side means and lie in the same BFS layer . Their tree paths up to their lowest common ancestor, at some depth , together with form a cycle of length , and no two-coloring survives an odd cycle, wherever it starts.
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?
- Nothing: each vertex is still first dequeued at its true distance
- It loops forever on graphs with cycles
- It never reaches some reachable vertices
- A vertex waiting in the queue can have its distance overwritten by a larger one, and the queue can receive 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 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 , , , , (neighbors in alphabetical order), dequeuing rewrites 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.
Why can a depth-first search of an undirected graph never produce a cross edge?
- Because undirected graphs have no cycles
- Because a neighbor that is still white when is discovered becomes 's descendant, so every edge joins an ancestor and a descendant
- Because DFS visits the neighbors in sorted order
- Because every vertex finishes before its neighbors are discovered
Show the answer
B. Because a neighbor that is still white when is discovered becomes 's descendant, so every edge joins an ancestor and a descendant
Take an edge with . At time , is white and adjacent to , so by the white-path theorem it becomes a descendant of . Edges between an ancestor and a descendant are tree or back edges; a cross edge would need its ends in different branches.
Go deeper
- Bridges, Articulation Points & Biconnectivity · Low-link values and the edges whose removal disconnects a graph.
- Implicit Graphs & BFS Variants · Grids and state spaces; multi-source, 0-1 and bidirectional BFS.
- Euler Tours & Hamiltonian Paths · Hierholzer’s linear-time algorithm, and its NP-hard cousin.
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.