Breadth-first and depth-first search each visit every vertex once and read each adjacency list once, in time O(V + E). They differ only in order. On this 8-town map, BFS reaches H by 4 roads, the fewest possible. DFS reaches it by 6.
Pick BFS or DFS and press Run. Watch which towns turn warm (found) and teal (finished). Then we build, piece by piece: storing a graph, the BFS ripple, DFS clocks, cycles, topological order and strongly connected components.
You need queues and stacks, recursion and a little Python. We build the rest from zero.
Based on Chapter 22 of Introduction to Algorithms (CLRS, third edition) by Cormen, Leiserson, Rivest and Stein. It follows Chapter 21, Disjoint Sets. The explanations, toys and devices are our own.
A made-up map: 8 towns, 10 two-way roads. Each town lists its neighbours in alphabetical order. The number in each town is the order in which the search found it.
Chapter 0
Write one small graph as a list and as a matrix, then grow it until the matrix no longer fits
Six courses depend on each other. Course A unlocks B and C. B and C both unlock D. C unlocks E, and D unlocks F.
Which courses can you reach from A? In what order should you take them? Every question in this lesson starts from a picture like this.
A graph G = (V, E) is a set of vertices V (the dots) and a set of edges E (the links between pairs of dots). In a directed graph, an edge u → v goes one way, like a prerequisite. In an undirected graph, an edge goes both ways, like a two-way road. We write V and E for the counts too.
A program must store the graph. CLRS gives two ways. An adjacency list keeps, for each vertex u, a list Adj[u] of the vertices that u points to. An adjacency matrix is a V by V table with a 1 in row u, column v when the edge u → v exists.
How much memory does each one take? Count the cells. Call the number of vertices V and the number of edges E.
Cells-list equals V plus E. Cells-matrix equals V squared.
The list pays for what exists: V heads plus one entry for each of the E edges. The matrix pays for every possible pair, V times V, even when most cells hold 0.
The course graph has V = 6 and E = 6. The list needs 6 + 6 = 12 cells. The matrix needs 6 × 6 = 36 cells, and 30 of them are 0.
Switch between the two layouts of the course graph. Then drag the size. Each vertex keeps 3 edges out, so E = 3V.
We made up the course graph. The bars count cells, not bytes, on a log scale where each grid line is 10 times the last.
A graph is sparse when E is close to V, and dense when E is close to V2. Road maps, link graphs and course catalogues are sparse. Every algorithm in this lesson reads each list once, so with lists it runs in O(V + E). With a matrix, finding the neighbours of one vertex means scanning a whole row, so the same algorithms cost O(V2).
| Question | Adjacency list | Adjacency matrix |
|---|---|---|
| Memory | V + E cells | V2 cells |
| All neighbours of u | out-degree of u | V (a full row) |
| Is u → v an edge? | scan Adj[u] | one lookup |
The failure. Symptom: a graph of one million vertices crashes the program at load time. Measure: V2 = 1012 cells; at one byte each that is a terabyte. Fix: store lists. With 3 edges per vertex the list holds 4 million cells.
Chapter 1
Step a queue through the course graph and watch distances grow one ring at a time
Drop a stone in a pond. The ring at 1 metre forms before the ring at 2 metres. Breadth-first search (BFS) explores a graph the same way. From a source vertex s, it finds every vertex 1 edge away, then every vertex 2 edges away, and so on.
BFS gives each vertex one of three colours. White means not found yet. Gray means found and waiting in the queue: the frontier. Black means finished: BFS has checked every edge out of it. A queue is first in, first out, so vertices leave in the order they joined.
Step 3 is the whole idea. Call the vertex we take u and its white neighbour v. Call the distance from s to u d[u], and v's parent in the search π[v].
d of v equals d of u plus one, and pi of v equals u.
When u finds a white vertex v, v is one edge farther from s than u. Write that distance into d[v] and remember u as v's parent. Each vertex gets this once, the first time BFS finds it.
B finds D, and d[B] = 1. So d[D] = 1 + 1 = 2 and π[D] = B. Later C also points to D, but D is already gray, so nothing changes.
Each step takes one vertex from the front of the queue. Warm is the frontier, teal is finished. The tag under each vertex is its distance.
The course graph of Chapter 0: A → B, A → C, B → D, C → D, C → E, D → F. Each vertex takes its neighbours in alphabetical order.
| Take | Finds | Queue after | Distances so far |
|---|---|---|---|
| A | B, C | B, C | A 0, B 1, C 1 |
| B | D | C, D | D 2 |
| C | E (D is gray) | D, E | E 2 |
| D | F | E, F | F 3 |
| E, then F | nothing | empty | done |
Read the path to F from the parents: F came from D, D from B, B from A. So A → B → D → F, 3 edges. Because the queue releases every distance-1 vertex before any distance-2 vertex, d[v] is the shortest number of edges from s. CLRS proves this as Theorem 22.5.
The failure. Symptom: BFS on a dense graph runs out of memory. Measure: count how often each vertex enters the queue. Fix: mark v gray when you add it, not when you take it out. Otherwise D enters twice here, once from B and once from C. A vertex with k edges into it can enter up to k times.
Chapter 2
Count the work line by line, then use the rings to split a graph into two sides
How long does BFS take on a graph with a million vertices? Count the work. Each vertex enters the queue at most once, because only white vertices enter and they turn gray at once. When a vertex leaves, BFS reads its list once.
Call the out-degree of u, the length of its list, |Adj[u]|. Taking u from the queue costs 1 step plus 1 step per list entry.
T equals the sum over u of one plus the size of Adj of u, which equals V plus E.
Give each vertex 1 step, and give it 1 more step for each entry in its list. The ones add up to V. The list lengths add up to E, because every edge sits in exactly one list.
Course graph: A costs 1 + 2, B 1 + 1, C 1 + 2, D 1 + 1, E 1 + 0, F 1 + 0. T = 3 + 2 + 3 + 2 + 1 + 1 = 12 = 6 + 6. On the 8-town map, each road sits in two lists, so T = 8 + 2 × 10 = 28.
Can you split a class into two teams so that no two friends share a team? A graph where this works is bipartite: each edge joins the two sides. Run BFS and give each vertex the side opposite its parent. If an edge ever joins two vertices of the same side, the answer is no.
Pick a graph and press Step. Side 0 is a blue ring, side 1 is solid blue. A red edge joins two vertices on the same side.
Made-up graphs. The test starts at A and takes neighbours in alphabetical order.
A worked number. The square A–B, B–C, C–D, D–A splits as {A, C} and {B, D}. Add B–D. BFS puts B and D both on side 1, because both are neighbours of A. The edge B–D closes the triangle A, B, D. A cycle of odd length can never be two-coloured, so the graph is not bipartite.
| Question | How BFS answers it |
|---|---|
| Fewest hops from s | d[v] and the parent pointers |
| Connected groups | start a new BFS at each vertex still white; each run is one group |
| Nearest of many sources | put every source in the queue at distance 0, then run as usual |
| Bipartite? | give each vertex the side opposite its parent; look for a same-side edge |
The failure. Symptom: the test says "bipartite" for a graph with a triangle. Measure: count the vertices that got a side; some stayed white. Fix: the triangle sat in a second piece of the graph. Loop over all vertices and start a fresh BFS at each white one.
Chapter 3
Dive down one path, stamp each vertex when you enter and when you leave, and read the family tree from the stamps
In a maze, you follow one corridor to its end. Then you back up to the last fork and try the next corridor. Depth-first search (DFS) does this. It goes deep first and backs up only at a dead end. Recursion does the backing up for free: the call stack remembers the forks.
DFS keeps one global clock that starts at 0. When DFS enters a vertex u, the clock ticks and DFS writes the discovery time d[u]. When DFS has checked every edge out of u, the clock ticks again and DFS writes the finish time f[u]. With V vertices, the stamps run from 1 to 2V.
The stamps hold the family tree. Take two vertices: an older one u and a younger one v. Call the stamps d[u], f[u], d[v] and f[v].
d of u is less than d of v, which is less than f of v, which is less than f of u.
Draw each vertex as an interval from d to f. If v's interval sits inside u's, v is a descendant of u in the DFS tree. If the two intervals do not touch, neither is a descendant of the other. They never half overlap. This is the parenthesis theorem (CLRS Theorem 22.7).
B is [2, 9] and E is [4, 7]. 2 < 4 < 7 < 9, so E is a descendant of B. D is [10, 11]. It starts after B ends, so D and B are in separate branches.
Each step is one event: enter, check an edge, or leave. The bars below are the intervals from d to f. Watch them nest.
A made-up graph: A → B, A → D, B → C, C → E, D → B, E → F, F → C. Neighbours in alphabetical order.
The full run gives A [1, 12], B [2, 9], C [3, 8], E [4, 7], F [5, 6] and D [10, 11]. Write an open bracket at each d and a close bracket at each f. You get (A (B (C (E (F F) E) C) B) (D D) A). The brackets always match.
The cost is the same as BFS. DFS enters each vertex once and reads each list once, so it runs in O(V + E).
The failure. Symptom: recursive DFS on a long chain of 5,000 vertices stops with RecursionError. Measure: Python's default recursion limit is 1,000 calls. Fix: keep your own stack of (vertex, next neighbour) pairs and loop, as the code in Chapter 9 does.
Chapter 4
Sort every edge into one of four kinds by the colour of its far end, and find cycles for free
Two build steps wait on each other: A needs B, and B needs A. The build hangs. How does a program see that before it starts? DFS answers with one look at a colour.
When DFS at u checks an edge u → v, the colour of v says what kind of edge it is.
| Kind | v is | Meaning | Stamps |
|---|---|---|---|
| Tree | white | u discovers v; the edge joins the DFS tree | d[u] < d[v] |
| Back | gray | v is an ancestor still on the stack | d[v] < d[u], v not finished |
| Forward | black | v is a finished descendant of u | d[u] < d[v] |
| Cross | black | v is finished, in another branch | d[v] < d[u] |
A back edge u → v closes a loop: the tree path from v down to u, plus the edge back up to v. The reverse also holds. If the graph has a cycle, take the first cycle vertex DFS enters. DFS reaches every other cycle vertex from it through white vertices, so all become its descendants. The edge from the last one back to it is a back edge. So a directed graph has a cycle exactly when DFS finds a back edge (CLRS Lemma 22.11).
Pick a variant and press Run. Each edge takes its kind's colour the moment DFS checks it.
The graph of Chapter 3. "A tries D first" only reorders A's list to D, B.
A worked number, on the Chapter 3 graph. Five edges are tree edges. F → C finds C gray, so it is a back edge: the cycle C → E → F → C. D → B finds B black with d[B] = 2 < d[D] = 10, so it is a cross edge. Remove F → C and no back edge is left: the graph is a DAG, a directed acyclic graph.
In an undirected graph only two kinds appear: tree and back. The edge you came in on is not a cycle, so skip the parent; any other visited neighbour closes one.
The failure. Symptom: a cycle check reports cycles in a graph that has none. Measure: print the edge it blamed. Here it would blame D → B, a cross edge. Fix: use three colours, not a visited set. Only a gray target means a cycle.
Chapter 5
Line up the courses two ways, by finish time and by peeling, and watch a cycle stop the line
Six courses: CS101 unlocks CS201, MATH101 unlocks MATH201, both CS201 and MATH201 unlock CS301, and CS301 unlocks CS401. You need a line of all six where every prerequisite comes before the course it unlocks. That line is a topological order. It exists only for a DAG.
DFS gives one for free. In a DAG there is no back edge. So for every edge u → v, DFS finishes v before it finishes u. Call the finish times f[u] and f[v].
f of u is greater than f of v, for every edge from u to v.
When DFS checks u → v, v is white, so it finishes inside u's call, or v is black and finished already. It cannot be gray, because gray means a cycle. Either way f[v] comes first. So list the vertices by f, largest first (CLRS Theorem 22.12).
DFS starting at CS101 gives f: CS401 5, CS301 6, CS201 7, CS101 8, MATH201 11, MATH101 12. The edge MATH201 → CS301 has 11 > 6. Largest first: MATH101, MATH201, CS101, CS201, CS301, CS401.
Kahn's algorithm builds an order without DFS. The in-degree of a vertex is the number of edges into it. A vertex with in-degree 0 has no prerequisite left, so it can go next.
Choose a method and step it. The tag under each course is its in-degree (Kahn) or its stamps (DFS). Then add the cycle.
A made-up catalogue. Both methods start from the courses in the order listed: CS101, MATH101, CS201, MATH201, CS301, CS401.
Kahn gives CS101, MATH101, CS201, MATH201, CS301, CS401. DFS gave a different line. Both are valid, because CS101 and MATH101 do not depend on each other. A DAG has exactly one topological order only when an edge joins every pair of neighbours in the line.
The failure. Symptom: a scheduler silently drops three courses. Measure: with CS401 → CS201 added, Kahn outputs CS101, MATH101, MATH201 and stops; CS201, CS301 and CS401 never reach in-degree 0. Fix: compare the output length with V and report the leftover vertices as the cycle.
Chapter 6
Run DFS once forwards and once on the reversed graph, and the groups fall out one by one
Packages A, B and C import each other in a loop. So do D, E and F. C also imports D, and E imports G. Which packages must ship together? Those that can reach each other both ways.
A strongly connected component (SCC) is a largest set of vertices where every vertex can reach every other along directed edges. Squash each SCC into one dot and the result, the component graph, is always a DAG. If two SCCs reached each other, they would be one SCC.
Kosaraju's algorithm (the one CLRS gives) has three steps.
Why does step 3 work? Call the largest finish time inside a component C its f(C).
If an edge goes from C to C-prime, then f of C is greater than f of C-prime.
C can reach C′, so DFS cannot finish all of C before it finishes all of C′ (CLRS Lemma 22.14). So the vertex with the largest finish time sits in a source component. In GT its edges to other components point inward, so DFS from it cannot leave its own SCC.
Step 1 gives f({A, B, C}) = 14, f({D, E, F}) = 11, f({G}) = 9. The edges C → D and E → G go from higher to lower: 14 > 11 and 11 > 9.
Pass 1 stamps finish times on G. Then the arrows flip. Pass 2 grows one green group per tree, in the order of the finish list.
Made-up packages with 8 edges: A → B, B → C, C → A, C → D, D → E, E → F, F → D and E → G. DFS starts at A; lists are alphabetical.
The worked run. Pass 1 visits A, B, C, D, E, F (F → D is a back edge), then G. Finish times, largest first: A 14, B 13, C 12, D 11, E 10, G 9, F 7. Pass 2 starts at A in GT and reaches C and B: SCC 1. The next white vertex in the list is D: it reaches F and E, SCC 2. Then G alone, SCC 3.
Both passes and the transpose cost O(V + E) each, so the whole algorithm is O(V + E).
The failure. Symptom: two separate loops come out as one component. Measure: check the order of pass 2. Started at the smallest finish time, F, it collects F, E, D, C, B and A as one group. Fix: pass 2 must go in decreasing finish time, on GT, not on G.
Chapter 7
Track the oldest vertex each subtree can reach, and pop a whole SCC the moment its root finishes
Kosaraju needs a second graph and a second pass. Robert Tarjan (1972) found the SCCs in one DFS. The trick is one extra number per vertex.
Tarjan's version keeps its own stack S of vertices with no SCC yet. A vertex joins S when DFS enters it. Its low-link low[u] is the smallest discovery time that u's subtree reaches. The subtree may use tree edges plus one edge to a vertex still on S. Call u's discovery time d[u].
low of u equals the minimum of d of u, low of w, and d of v.
Start low[u] at d[u]. After each child returns, take its low if smaller. For an edge to a vertex still on S, take that vertex's d if smaller. Suppose u finishes with low[u] = d[u]. Then nothing below u reaches older, so u is the root of an SCC: pop S down to u.
Clock from 1: d[D] = 4, d[E] = 5, d[F] = 6. F → D, and D is on S, so low[F] = min(6, 4) = 4. G is its own root, with low 7 = d 7. So low[E] = min(5, 4, 7) = 4. low[D] = min(4, 4) = 4 = d[D], so pop F, E, D.
Each vertex shows d / low. The stack S runs along the bottom. A vertex turns green when its SCC pops.
The packages of Chapter 6. The bug version also starts its outer loop at D, which makes the bug show.
The correct run pops {G}, then {F, E, D}, then {C, B, A}: the SCCs come out in reverse topological order of the component graph. It is O(V + E), with one pass and no transpose.
The failure. Symptom: some vertices never get an SCC. Measure: start at D. D, E, F and G finish and pop first. Then C → D sees D, finished and off the stack, and the bug takes d[D] = 1. Now low[C] = low[B] = low[A] = 1, below their own d, so no root pops A, B and C. Fix: only lower low[u] with d[v] when v is still on S.
Chapter 8
Grow a chain, a star and a tree, and see which search holds more vertices at once
Both searches cost O(V + E) time. They differ in what they answer and in how much they hold in memory at one moment.
| Question | Use | Why |
|---|---|---|
| Fewest hops | BFS | the queue releases distances in order |
| Bipartite? | BFS | sides follow the rings |
| Cycle in a directed graph | DFS | a back edge is a gray target |
| Topological order | DFS or Kahn | finish times, or in-degree peeling |
| SCCs | DFS | finish times (Kosaraju) or low-links (Tarjan) |
| Reachable at all | either | both visit everything reachable |
The memory differs by shape. BFS holds one whole ring in its queue. DFS holds one root-to-leaf path on its stack.
Pick a shape and drag its size. Both searches start at the warm vertex. The bars show the most vertices each holds at one moment.
The peaks are measured by running both searches on the drawn graph. The binary tree is rounded down to a full tree of 3, 7, 15, 31 or 63 vertices.
Now a search between two given vertices s and t. Call the branching factor b, the number of new neighbours per vertex, and the distance from s to t d. Bidirectional BFS runs one BFS from s and one from t, and stops when the two frontiers meet.
N-one-way is about b to the d. N-two-way is about two times b to the d over two.
Each ring is b times bigger than the last, so most of the work is in the outer ring. Two searches that each go half way skip all the big outer rings.
With made-up numbers b = 10 and d = 6: one way touches about 106 = 1,000,000 vertices. Two ways touch about 2 × 103 = 2,000. That is 500 times less.
The failure. Symptom: a path finder that uses DFS returns a 6-hop route when a 4-hop route exists, as in the hero. Measure: compare its path length with d[t] from BFS. Fix: DFS finds a path, not the shortest; use BFS for fewest hops.
Chapter 9
Keep the terms, the numbers, the checks and the code in one place
Every algorithm here visits each vertex once and reads each adjacency list once. They differ in the order of the visit: a queue or a stack. They also differ in what they write down: distances, sides, clock stamps, in-degrees or low-links.
| Term | Meaning | Number from this lesson |
|---|---|---|
| Adjacency list | one list of out-neighbours per vertex; V + E cells | courses: 12 cells against 36 |
| BFS | queue; d[v] = d[u] + 1 on first discovery | A to F: 3 edges |
| Bipartite test | side opposite the parent; a same-side edge means an odd cycle | square plus B–D: triangle A, B, D |
| DFS stamps | d on entry, f on exit, one clock from 1 to 2V | A [1, 12], B [2, 9], D [10, 11] |
| Back edge | edge to a gray vertex; exists exactly when there is a cycle | F → C closes C, E, F |
| Topological order | decreasing finish time, or Kahn's peeling | MATH101 first, f = 12 |
| Kosaraju | DFS on G, then DFS on GT by decreasing f | f(C): 14, 11, 9 |
| Tarjan | one DFS; pop when low[u] = d[u] | low[F] = 4 = d[D] |
| Bidirectional BFS | two half searches meet | b = 10, d = 6: 2,000 against 1,000,000 |
pythonfrom collections import deque def bfs(G, s): # G: dict vertex -> list of neighbours d, parent = {s: 0}, {s: None} q = deque([s]) while q: u = q.popleft() for v in G[u]: if v not in d: # white: mark on discovery d[v], parent[v] = d[u] + 1, u q.append(v) return d, parent def dfs_stamps(G): # iterative: no recursion limit d, f, t = {}, {}, 0 for s in G: if s in d: continue t += 1; d[s] = t stack = [(s, iter(G[s]))] while stack: u, it = stack[-1] v = next(it, None) if v is None: # every edge of u is done t += 1; f[u] = t; stack.pop() elif v not in d: t += 1; d[v] = t; stack.append((v, iter(G[v]))) return d, f def topo_order(G): # Kahn; raises on a cycle indeg = {v: 0 for v in G} for u in G: for v in G[u]: indeg[v] += 1 q = deque(v for v in G if indeg[v] == 0); out = [] while q: u = q.popleft(); out.append(u) for v in G[u]: indeg[v] -= 1 if indeg[v] == 0: q.append(v) if len(out) < len(G): raise ValueError('cycle among ' + str([v for v in G if indeg[v] > 0])) return out def kosaraju(G): _, f = dfs_stamps(G) GT = {v: [] for v in G} for u in G: for v in G[u]: GT[v].append(u) # reverse every edge seen, sccs = set(), [] for s in sorted(G, key=f.get, reverse=True): # largest finish first if s in seen: continue comp, stack = [], [s]; seen.add(s) while stack: u = stack.pop(); comp.append(u) for v in GT[u]: if v not in seen: seen.add(v); stack.append(v) sccs.append(comp) return sccs
These four tools are the floor of graph algorithms. Add edge weights and BFS's queue becomes Dijkstra's priority queue. Edmonds and Karp find each augmenting path in a flow network with BFS. 2-SAT is solved by finding the SCCs of an implication graph.
Now press Present or Teach and explain from memory. Say why BFS gives fewest hops and what the two DFS stamps mean. Say why a back edge is a cycle and why finish order sorts a DAG. Say why Kosaraju starts pass 2 at the largest finish time. Then go back to the map and run both searches again. This time say which chapter explains each colour.
This lesson re-teaches Chapter 22, Elementary Graph Algorithms, of Introduction to Algorithms (third edition) by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press). Theorem and lemma numbers follow that edition.
Tarjan's algorithm is from Robert Tarjan's 1972 paper "Depth-First Search and Linear Graph Algorithms". Kahn's algorithm is from Arthur Kahn (1962). The text, toys and devices here are our own.