Elementary Graph Algorithms

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.

Search the map two ways

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

A Graph, and Two Ways to Store It

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.

Say it aloud

Cells-list equals V plus E. Cells-matrix equals V squared.

cellslist
cells-list the memory an adjacency list needs: one slot per vertex for its list head, one entry per edge.
V
V the number of vertices.
E
E the number of directed edges. An undirected edge takes two entries, one at each end.
cellsmatrix
cells-matrix the memory an adjacency matrix needs, edges or not.
V2
V squared V rows times V columns.
In plain words

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.

With numbers

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.

Grow the graph until the matrix breaks

Switch between the two layouts of the course graph. Then drag the size. Each vertex keeps 3 edges out, so E = 3V.

1,000

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).

QuestionAdjacency listAdjacency matrix
MemoryV + E cellsV2 cells
All neighbours of uout-degree of uV (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.

The road

  1. Breadth-first search: the ripple that finds the fewest hops.
  2. Cost and uses of BFS: why it is O(V + E), and the two-colour test.
  3. Depth-first search: one clock, two stamps per vertex.
  4. Edge types and cycles: a back edge means a cycle.
  5. Topological sort: order a DAG by finish time, or by peeling.
  6. Strongly connected components: Kosaraju's two passes.
  7. Tarjan's low-link: the same groups in one pass.
  8. BFS or DFS: memory shape and meeting in the middle.
  9. Field guide: the table, the checklist, the code.
A graph has 10,000 vertices and 20,000 directed edges. How many cells do the list and the matrix need?

Chapter 1

Breadth-First Search: The Ripple

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.

  1. Paint s gray, set its distance to 0, and put it in the queue.
  2. Take the vertex u at the front of the queue.
  3. For each white neighbour v of u: paint v gray, set its distance and parent, and add v to the back.
  4. Paint u black. Go to step 2 until the queue is empty.

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].

Say it aloud

d of v equals d of u plus one, and pi of v equals u.

d[v]
d of v the number of edges from the source s to v. It starts at infinity for every vertex but s.
d[u]
d of u the distance of the vertex we took from the front of the queue.
+ 1
plus one one more edge: the edge u → v.
π[v]
pi of v the parent of v: the vertex that found it. Following parents back gives the path.
u
u the vertex BFS works on now.
In plain words

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.

With numbers

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.

Step the queue

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.

TakeFindsQueue afterDistances so far
AB, CB, CA 0, B 1, C 1
BDC, DD 2
CE (D is gray)D, EE 2
DFE, FF 3
E, then Fnothingemptydone

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.

BFS takes u with d[u] = 3 and finds a white neighbour v. What is d[v]?

Chapter 2

What BFS Costs, and What It Answers

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.

Say it aloud

T equals the sum over u of one plus the size of Adj of u, which equals V plus E.

T
T the total steps of the main loop.
Σu
the sum over u add one term for every vertex that leaves the queue.
1
one the step that takes u out and paints it black.
|Adj[u]|
the size of Adj of u one step per neighbour of u that BFS checks.
V + E
V plus E the V ones add to V, and the list lengths add to E.
In plain words

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.

With numbers

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.

The two-colour test

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.

Two-colour the graph

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.

QuestionHow BFS answers it
Fewest hops from sd[v] and the parent pointers
Connected groupsstart a new BFS at each vertex still white; each run is one group
Nearest of many sourcesput 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.

The two-colour test finds an edge whose two ends are both on side 0. What does that prove?

Chapter 3

Depth-First Search: One Clock, Two Stamps

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.

  1. Tick the clock. Set d[u]. Paint u gray.
  2. For each neighbour v of u: if v is white, set π[v] = u and visit v.
  3. Paint u black. Tick the clock. Set f[u].
  4. In the outer loop, visit every vertex that is still white.

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].

Say it aloud

d of u is less than d of v, which is less than f of v, which is less than f of u.

d[u]
d of u the clock reading when DFS entered u.
d[v]
d of v the clock reading when DFS entered v.
f[v]
f of v the clock reading when DFS left v for good.
f[u]
f of u the clock reading when DFS left u for good.
In plain words

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).

With numbers

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.

Run the clock

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.

DFS stamps u as [3, 10] and v as [5, 6]. What is v to u?

Chapter 4

Edge Types, and the Edge That Means a Cycle

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.

Kindv isMeaningStamps
Treewhiteu discovers v; the edge joins the DFS treed[u] < d[v]
Backgrayv is an ancestor still on the stackd[v] < d[u], v not finished
Forwardblackv is a finished descendant of ud[u] < d[v]
Crossblackv is finished, in another branchd[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).

Classify every edge

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.

DFS at u checks u → v and finds v gray. What follows?

Chapter 5

Topological Sort: Order a DAG

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].

Say it aloud

f of u is greater than f of v, for every edge from u to v.

f[u]
f of u the finish time of the edge's tail, the prerequisite.
>
is greater than later on the DFS clock.
f[v]
f of v the finish time of the edge's head, the course it unlocks.
u → v
u to v any edge of the DAG.
In plain words

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).

With numbers

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.

  1. Put every vertex with in-degree 0 in a queue.
  2. Take u, append it to the order, and lower the in-degree of each v in Adj[u] by 1.
  3. When a v reaches 0, add it to the queue. Repeat until the queue is empty.
  4. If fewer than V vertices came out, the rest sit on a cycle.

Line up the courses

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.

Kahn's algorithm outputs 8 of 10 vertices, then the queue is empty. Why?

Chapter 6

Strongly Connected Components: Kosaraju's Two Passes

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.

  1. Run DFS on G and record every finish time.
  2. Build the transpose GT: the same vertices, every edge reversed.
  3. Run DFS on GT, starting each new tree at the white vertex with the largest finish time. Each tree is one SCC.

Why does step 3 work? Call the largest finish time inside a component C its f(C).

Say it aloud

If an edge goes from C to C-prime, then f of C is greater than f of C-prime.

C → C′
C to C-prime some edge leaves component C and enters a different component C′.
f(C)
f of C the largest finish time of any vertex in C, from step 1.
>
is greater than finishes later.
f(C′)
f of C-prime the largest finish time in C′.
In plain words

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.

With numbers

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.

Peel the components

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.

In pass 2 of Kosaraju's algorithm, why start at the vertex with the largest finish time?

Chapter 7

Tarjan's Low-Link: The Same Groups in One Pass

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].

Say it aloud

low of u equals the minimum of d of u, low of w, and d of v.

low[u]
low of u the oldest discovery time u's subtree can reach and still be in u's group.
min
the minimum of the smallest value in the list.
d[u]
d of u u's own discovery time: the starting value.
low[w]
low of w for each tree child w, after w's call returns.
d[v]
d of v for each edge u → v where v is already found and still on the stack S.
In plain words

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.

With numbers

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.

Watch low fall, then pop

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.

Vertex u finishes its loop with d[u] = 5 and low[u] = 5. What does Tarjan's algorithm do?

Chapter 8

BFS or DFS: Memory Shape and Meeting in the Middle

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.

QuestionUseWhy
Fewest hopsBFSthe queue releases distances in order
Bipartite?BFSsides follow the rings
Cycle in a directed graphDFSa back edge is a gray target
Topological orderDFS or Kahnfinish times, or in-degree peeling
SCCsDFSfinish times (Kosaraju) or low-links (Tarjan)
Reachable at alleitherboth 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.

Grow the shape

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.

31

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.

Say it aloud

N-one-way is about b to the d. N-two-way is about two times b to the d over two.

None-way
N-one-way the vertices one BFS from s touches before it reaches t.
bd
b to the d b new vertices per vertex, for d rings: b times itself d times.
Ntwo-way
N-two-way the vertices both searches touch together.
2
two two searches.
bd/2
b to the d over two each search only goes half way, d/2 rings.
In plain words

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 numbers

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.

A star has one centre joined to 999 leaves. Search from the centre. Which holds more vertices at one moment?

Chapter 9

Field Guide

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.

TermMeaningNumber from this lesson
Adjacency listone list of out-neighbours per vertex; V + E cellscourses: 12 cells against 36
BFSqueue; d[v] = d[u] + 1 on first discoveryA to F: 3 edges
Bipartite testside opposite the parent; a same-side edge means an odd cyclesquare plus B–D: triangle A, B, D
DFS stampsd on entry, f on exit, one clock from 1 to 2VA [1, 12], B [2, 9], D [10, 11]
Back edgeedge to a gray vertex; exists exactly when there is a cycleF → C closes C, E, F
Topological orderdecreasing finish time, or Kahn's peelingMATH101 first, f = 12
KosarajuDFS on G, then DFS on GT by decreasing ff(C): 14, 11, 9
Tarjanone DFS; pop when low[u] = d[u]low[F] = 4 = d[D]
Bidirectional BFStwo half searches meetb = 10, d = 6: 2,000 against 1,000,000

Check before you trust a traversal

  1. Use adjacency lists unless the graph is small or dense.
  2. Mark a vertex when you discover it, not when you finish it.
  3. Loop over every vertex, so separate pieces of the graph are not missed.
  4. For directed cycles, use three colours: only a gray target is a cycle.
  5. For topological order, check that the output has V vertices.
  6. On deep graphs in Python, use an explicit stack, not recursion.

The core, in code

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

Where it sits in the field

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.

Keep going

The takeaway. Pick the order that answers your question. A queue gives distances. A stack gives clock stamps, and the stamps give cycles, orders and components.
You need the fewest network hops between two servers in a graph of 50,000 servers and 200,000 links. What do you run?

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.

Credit and source

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.

CLRS Chapter 22: Elementary Graph Algorithms
Introduction to Algorithms (MIT Press) · Back to Gleams