Module contents
Lesson 18 of 33Core 105 min

Depth-first search, topological sort and components

Build linear graph traversals, topological orders, strongly connected components, bridges and articulation points, with proofs and practical representations.

After this lesson you can

  • Choose graph representations based on density and required operations, including CSR.
  • Prove the parenthesis theorem and classify DFS edges.
  • Implement Kahn and DFS topological sorting and detect cycles with a certificate.
  • Implement iterative Tarjan strongly connected components and build the condensation graph.
  • Detect bridges and articulation points using low values.

Before you start

Motivation: ordering dependencies

A build system receives four hundred modules and a list of who imports whom. Before compiling a module, everything it imports must already be compiled. The first question is whether an order respects that; the second is which order; and if none exists, the useful message is not merely “there is a cycle” but “these three modules import each other in a circle, and this import closes it”. All three questions can be answered in linear time with the same tool: depth-first search recording when each vertex is discovered and finished.

That structure appears in very different places:

  • Software builds. make, cargo or a package manager’s dependency resolver orders a dependency graph. Cycles are Python’s ImportError: cannot import name ... (most likely due to a circular import).
  • Autograd. A network’s computational graph is acyclic: the backward pass (backpropagation) can compute a node’s gradient only after all consumers have contributed theirs, traversing nodes in reverse topological order.
  • Mutual recursion. In a program’s call graph, cycles are functions calling each other. A compiler or static analyzer groups definitions into strongly connected components and processes each group after everything it depends on. Haskell uses this for type inference (the Haskell Report calls it dependency analysis).
  • Logic. Deciding a formula with two-literal clauses (2-SAT) reduces to strongly connected components of an implication graph, as proved below.
  • Networks. Which link or node, if removed, splits a network in two: bridges and articulation points.

The lesson follows that order: first graph storage and operation costs, then depth-first search and its theory (the parenthesis and white-path theorems), and on that foundation topological order, strongly connected components with Kosaraju and Tarjan, and bridges. Basic graph vocabulary (definitions, paths and connectivity, directed acyclic graphs) is assumed from discrete mathematics; algorithms and analysis are new here. We use G=(V,E)G = (V, E) with n=∣V∣n = \abs{V} vertices numbered 0,…,n−10, \dots, n-1, and m=∣E∣m = \abs{E} edges; the graph is directed unless stated otherwise.

Graph representations and their costs

Mathematics does not distinguish ways of storing a graph; algorithms do. What matters is which operations are needed and how often.

Three representations cover almost everything:

  • Adjacency matrix. A∈{0,1}n×n\mat{A} \in \{0, 1\}^{n \times n} with auv=1a_{uv} = 1 if (u,v)∈E(u, v) \in E. It occupies Θ(n2)\Theta(n^2) cells even with few edges.
  • Adjacency lists. For each uu, a list of outgoing neighbors. Occupies Θ(n+m)\Theta(n + m).
  • CSR (compressed sparse row, the scipy.sparse format). All lists concatenated in one array indices of length mm, plus array indptr of length n+1n + 1 such that neighbors of uu are indices[indptr[u]:indptr[u+1]]. Slice length is the out-degree of uu.
RepresentationMemoryNeighbors of uuIs (u,v)∈E(u,v) \in E?Add edge
MatrixΘ(n2)\Theta(n^2)Θ(n)\Theta(n)O(1)\bigO(1)O(1)\bigO(1)
Adjacency listsΘ(n+m)\Theta(n + m)Θ(deg⁡u)\Theta(\deg u)O(deg⁡u)\bigO(\deg u)amortized O(1)\bigO(1) (with a dynamic array)
Lists with setsΘ(n+m)\Theta(n + m), large constantΘ(deg⁡u)\Theta(\deg u)expected O(1)\bigO(1)expected O(1)\bigO(1)
CSRΘ(n+m)\Theta(n + m), compactΘ(deg⁡u)\Theta(\deg u), contiguousO(log⁡deg⁡u)\bigO(\log \deg u) if row sortedO(n+m)\bigO(n + m): rebuild

CSR gives up modifications for compactness and locality: a vertex’s neighbors are consecutive in memory and traversal is a sequential read the processor can prefetch; Python’s list of lists follows pointers to scattered objects. The RAM model misses this difference (it counts reads, not cache misses), but in practice it matters as much as any constant. An undirected graph stores each edge twice, once per direction; a weighted graph adds array data parallel to indices, exactly what scipy.sparse.csr_matrix stores.

Building CSR from an edge list costs Θ(n+m)\Theta(n + m) with counting sort by source: count degrees, a prefix sum gives indptr, and one pass places each edge. The figure shows what each structure reads for two operations.

InteractiveOne graph, three representations
Matrix (n² cells)Adjacency lists01234560110:14111:2212:5313:0414:3515:6616:2CSR: two contiguous arraysindptr0021324354657687indices1041225304356627
Graph
Operation
0
Vertices, edges7, 8
Matrix reads7
List reads2
CSR reads4 (2 from indptr)
Neighbors of 0: 1, 4. The matrix scans its whole row (7 cells) even with few neighbors; lists and CSR read only 2. CSR stores them contiguously, between indptr[0] = 0 and indptr[1] = 2.
A directed graph of 7 vertices and 8 edges in the matrix (top left), adjacency lists (aligned with matrix rows), and CSR (bottom, with its two arrays). Initial state: ‘Neighbors of u’ with u = 0. The matrix reads its entire row (7 cells), while lists read 2 neighbors and CSR reads the contiguous indices slice between indptr[0] = 0 and indptr[1] = 2 (plus two indptr reads). Switch to ‘Does u→v exist?’ with v = 4: the matrix reads one cell, the list is traversed to 4 and CSR uses binary search with numbered probes. Click matrix cells to draw your graph and switch to the dense graph: to traverse neighbors lists read 4 versus 7 row cells and CSR 6, so the advantage nearly disappears, while the matrix still wins edge queries with one read.

Memory matters too. A byte matrix for n=106n = 10^6 vertices occupies a terabyte even with only 16 neighbors per vertex; the same graph’s CSR uses 68 MB. The bit matrix (n2/8n^2/8 bytes) beats CSR with 32-bit indices, 4(n+1+m)4(n + 1 + m) bytes, when n2/8<4(n+1+m)n^2/8 < 4(n + 1 + m), that is, when mm exceeds approximately n2/32n^2/32: average degree n/32n/32. For millions of vertices this never happens; for a thousand vertices and degree 32 it already does.

InteractiveMemory by size and density
1 KB1 MB1 GB1 TB1 PB16 GBByte matrixn²1.00 TBBit matrixn²/8125 GBPython lists64n + 36m640 MBCSR (int32)4(n + 1 + m)68.0 MB
1,000,000
16
Edges m = n·d16,000,000
SmallestCSR 68.0 MB
Lists ÷ CSR9.4×
Bit-matrix crossoverd ≈ 31,250
With n = 1,000,000 and mean degree 16 (m = 16,000,000 edges), CSR uses 68.0 MB, 9.4 times less than Python lists and less than the bit matrix (125 GB). Fit in 16 GB: Python lists, CSR (int32).
Bytes per representation for a graph of n vertices and average degree d, on a logarithmic scale (each tick is a thousand times the previous). Initially n = 1 million and d = 16: the byte matrix occupies 1 TB, bit matrix 125 GB, Python lists 640 MB (model of 64 bytes per vertex and 36 per edge) and CSR 68 MB. Only the latter two fit within the dashed 16 GB line. Lower n to 1 000 and raise degree: at d = 16 CSR (68 KB) beats the bit matrix (125 KB), but at d = 32 the bit matrix (125 KB) is smaller than CSR (132 KB), the crossover at d ≈ n/32 predicted by the formula.

The Python-list model counts per edge an 8-byte pointer inside the list and a 28-byte int object (integers above 256 are not shared), and per vertex a list header. This is a model, not a measurement: below we measure a real graph, and in 32-bit Pyodide absolute figures are smaller. The expected conclusion holds: CSR is chosen because a graph of 10810^8 edges fits in 0.4 GB instead of several.

Breadth-first traversal: BFS in linear time

Breadth-first search (BFS) visits vertices in increasing distance layers from source ss using a queue: remove a vertex, inspect each neighbor, and label previously unlabeled ones with the vertex’s label plus one and enqueue them.

Proof

Induct on kk that vertices at distance kk receive label kk and enter the queue after all at distance k−1k - 1 and before any at distance k+1k + 1. For k=0k = 0 there is only ss. Assume true through kk. A vertex vv at distance k+1k + 1 has a predecessor uu at distance kk and none at a shorter distance (otherwise its own distance would be shorter). Since those at distance kk leave the queue before those at k+1k + 1, no vertex farther than k+1k + 1 can yet be discovered, because its predecessors are at distance at least k+1k + 1; when the first predecessor uu of vv leaves the queue, vv receives label k+1k + 1 if not already labeled (and could not have a smaller label by induction). Thus vv‘s label is k+1k + 1 and it enters after all vertices at distance kk. Each vertex enters at most once and its list is examined once: O(n+m)\bigO(n + m), including label initialization. With a matrix, one row of nn cells is scanned per dequeued vertex. ■\blacksquare

∎

BFS also returns a shortest-path tree in edges (parent of vv is its discoverer). The queue needs popleft in O(1)\bigO(1): with a Python list, cola.pop(0) shifts every element and makes traversal quadratic, a classic error measured in the lab. Search in implicit state spaces, where the graph is generated instead of stored, is covered in the search lesson; here graphs are in memory. BFS does not handle weighted shortest paths: use Dijkstra, replacing the queue with a priority queue.

Depth-first search: times, parentheses and edges

Depth-first search (DFS) replaces the queue with the recursion stack: follow an edge as far as possible, backtracking only when a vertex is exhausted. What matters is not visit order but two numbers recorded per vertex, with a clock ticking once per event.

DFS(G):                                    VISITAR(u):
  para cada vértice u: color[u] = blanco     reloj += 1;  d[u] = reloj;  color[u] = gris
  reloj = 0                                   para cada v en Adj[u]:
  para cada vértice u:                          si color[v] == blanco:  padre[v] = u;  VISITAR(v)
    si color[u] == blanco: VISITAR(u)         color[u] = negro;  reloj += 1;  f[u] = reloj

A vertex is white until discovered, gray while its call is open (discovered but not finished examining neighbors), and black when finished. Numbers d[u]d[u] (discovery) and f[u]f[u] (finish) are all distinct and range from 11 to 2n2n. Calls started by the main loop are roots of a search forest, and padre gives its tree edges. Each vertex is visited once and each adjacency list traversed once, costing Θ(n+m)\Theta(n + m) with lists or CSR.

InteractiveDFS with a timeline
TATCTRTRu1/8v2/7w9/12x4/5y3/6z10/11Intervals [d, f]: an open vertex grows to the current clock123456789101112u1/8v2/7w9/12x4/5y3/6z10/11
step 17 of 17
Graph
Neighbor order
  • tree (T)
  • back (R)
  • forward (A)
  • cross (C)
Clock12
Open vertices (stack)·
Tree, back, forward, cross4, 2, 1, 1
Edges examined8 of 8
Directed cycleyes (has R)
Done: every vertex has its [d, f] interval. The search forest contains 2 tree(s), and the clock reached 12 = 2n.
Initial state: completed search on a six-vertex graph exhibiting all four edge types. Press ⏮ then ▶ and watch the bars below: each vertex draws interval [d, f]; while gray its bar grows to the clock. When finished, click u's bar: v, y and x are contained within its interval (orange), while w and z are disjoint (dimmed); none partly overlaps. Letters T, R, A and C denote tree, back, forward and cross edges: this graph has 4, 2, 1 and 1. Change neighbor order to ‘Reverse’: times change and edge u→v becomes forward instead of tree, but intervals remain nested or disjoint. Choose ‘No cycles’ (no R) and draw an edge closing a cycle: an R appears.

What the figure shows is a theorem.

Proof

Without loss of generality let d[u]<d[v]d[u] < d[v]. There are two cases because all times differ.

If d[v]<f[u]d[v] < f[u], then vv is discovered while uu is gray, inside uu‘s open call. Everything discovered while a call is open hangs below it in the forest, so vv is a descendant of uu. Moreover vv‘s call finishes before uu‘s (calls nest like a stack), so f[v]<f[u]f[v] < f[u] and vv‘s interval is contained in uu‘s.

If f[u]<d[v]f[u] < d[v], intervals are disjoint. Neither is the other’s descendant: a descendant is discovered while its ancestor is gray, and here vv is discovered after uu finishes. The three cases are mutually exclusive because their time conditions are. ■\blacksquare

∎

The theorem describes times, but not when a vertex becomes another’s descendant. The second result answers that, relating graph structure to forest structure.

Proof

(⇒\Rightarrow) If vv is a descendant of uu, tree path u=w0,w1,…,wk=vu = w_0, w_1, \dots, w_k = v has every wiw_i with i≥1i \ge 1 as a descendant of uu, so they are discovered after uu: at d[u]d[u] they are white.

(⇐\Leftarrow) Let u=w0→w1→⋯→wk=vu = w_0 \to w_1 \to \dots \to w_k = v be a white path at time d[u]d[u], and suppose some wiw_i is not a descendant of uu. Take the first, wiw_i, with i≥1i \ge 1. Then wi−1w_{i-1} is a descendant of uu (or is uu), hence f[wi−1]≤f[u]f[w_{i-1}] \le f[u]. When edge wi−1→wiw_{i-1} \to w_i is examined, wiw_i is either white (then becomes a child of wi−1w_{i-1}, contradicting the assumption) or already discovered; either way it is discovered before wi−1w_{i-1} finishes. Since it was white at d[u]d[u], d[u]<d[wi]<f[wi−1]≤f[u]d[u] < d[w_i] < f[w_{i-1}] \le f[u], and by the parenthesis theorem wiw_i is a descendant of uu. Contradiction. ■\blacksquare

∎

Edge classification

Each edge (u,v)(u, v) is examined exactly once, when uu reaches it in its list, and vv‘s color then classifies it:

Color of vv when examining (u,v)(u,v)TypeIntervalsWhat vv is to uu
whitetreevv nested in uuchild
graybackuu nested in vv (or v=uv = u)ancestor
black, with d[u]<d[v]d[u] < d[v]forwardvv nested in uunon-child descendant
black, with d[v]<d[u]d[v] < d[u]crossdisjoint, f[v]<d[u]f[v] < d[u]neither

The table follows from the parenthesis theorem. If vv is gray, its call remains open and contains uu‘s: vv is an ancestor of uu (or uu itself for a loop). If vv is black and discovered after uu, its interval lies inside uu‘s. If black and discovered earlier, it cannot contain uu (because vv already finished and uu remains open), so the intervals are disjoint and f[v]<d[u]f[v] < d[u]. Classification depends on the search (vertex and neighbor order), not just the graph; what does not depend on it is what we prove using it.

Proof

Let {u,v}\{u, v\} be an edge and uu the endpoint from which it is first examined. If vv were black then, vv would have finished and examined all its edges, including {v,u}\{v, u\}: the edge would already have been examined, contradicting the assumption. Thus vv is white (tree) or gray (back). ■\blacksquare

∎

This absence of cross edges makes the structure of undirected graphs so clean in the final sections: everything that is not a tree edge connects a vertex to an ancestor.

Topological order

Proof

If there is a cycle v1→v2→⋯→vk→v1v_1 \to v_2 \to \dots \to v_k \to v_1, a topological order gives positions with σ(v1)<σ(v2)<⋯<σ(vk)<σ(v1)\sigma(v_1) < \sigma(v_2) < \dots < \sigma(v_k) < \sigma(v_1), absurd. Conversely, a DAG with n≥1n \ge 1 vertices has one without incoming edges: if every vertex had a predecessor, walking backward from any vertex would chain n+1n + 1 vertices and, by the pigeonhole principle, one repeats, closing a cycle. Place that vertex first, remove it, and induct on the remaining graph, still acyclic. ■\blacksquare

∎

The proof is already an algorithm, the first of two.

Kahn: remove sources

Kahn’s algorithm stores each vertex’s in-degree, maintains a queue of those with degree 00 and repeats: remove one, append it to the order and decrement its successors’ degrees; those reaching 00 enter the queue. Cost Θ(n+m)\Theta(n + m) with lists or CSR.

Proof

A vertex enters the order when all its predecessors already have, so edges always point forward. If the algorithm stops with R≠∅R \ne \emptyset, no vertex of RR has remaining degree 00, and vv‘s remaining degree counts predecessors of vv still unplaced, namely those in RR. Each vertex of RR therefore has at least one predecessor in RR, and the preceding pigeonhole argument yields a cycle within RR. If the graph is acyclic, R≠∅R \ne \emptyset cannot happen. ■\blacksquare

∎

This gives a certificate: the algorithm does not merely say “yes” or “no” but returns something independently checkable with less work than the original computation. Verify an order in O(n+m)\bigO(n + m) by checking every edge points forward, and a cycle in O(longitud)\bigO(\text{longitud}) by checking every step is an edge. This is the difference between “this cannot be ordered” and “this cannot be ordered, and here is the proof”.

DFS: order by finish time

The second algorithm follows from the parenthesis theorem. The idea: if edge u→vu \to v exists, vertex vv must finish before uu, because uu cannot close while vv remains pending.

Proof

For a tree or forward edge, vv descends from uu and its interval lies inside uu‘s, hence f[v]<f[u]f[v] < f[u]. For a cross edge, intervals are disjoint and f[v]<d[u]<f[u]f[v] < d[u] < f[u]. ■\blacksquare

∎
Proof

Without back edges, the lemma says every edge u→vu \to v satisfies f[v]<f[u]f[v] < f[u], so uu precedes vv in decreasing ff order. With back edge (u,v)(u, v), vv is gray, hence an ancestor of uu (or u=vu = v): the tree path from vv to uu and edge u→vu \to v form a cycle. ■\blacksquare

∎

Together these theorems also show that a directed graph is acyclic if and only if its DFS has no back edges; “cycle implies back edge” has a more direct proof using the white-path theorem, requested in the first exercise. Decreasing ff order needs no sorting: append each vertex to a list when it finishes and read it backward. The stated cycle comes from following padre from uu to vv.

Both algorithms are linear and yield similar results, but differ in character. Kahn works in waves (vertices freed simultaneously form a wave and can run in parallel, so the wave count is longest-path length plus one, the critical path); it underlies schedulers and can use a priority queue for, say, the lexicographically smallest order. DFS needs neither in-degrees nor the transpose and leads into components and bridges. Topological order is unique if and only if Kahn never has two vertices in its queue simultaneously, that is, if the graph has a path visiting every vertex.

A network’s backward pass as an example

An expression such as y=tanh⁡((ab+c)(ab⋅c))y = \tanh((a b + c)(a b \cdot c)) defines a graph: each operation is a node with edges to operands. To propagate gradients, visit each node after all consumers; a DFS postorder starting at yy and descending to operands puts operands before consumers, so reversing it is valid. The lab builds minimal autograd exactly this way and shows what happens using preorder (discovery order) instead of reverse postorder: the gradient is wrong because a node with two consumers propagates its gradient before receiving all of the second’s contribution. Karpathy’s micrograd implementation constructs the order with DFS; PyTorch autograd keeps a pending-dependency count per node and executes it at zero, which is Kahn.

Strongly connected components

In an undirected graph, “reachable from” is symmetric and connected components are its equivalence classes. In a directed graph we require both directions.

Proof

A cycle C1→C2→⋯→Ck→C1C_1 \to C_2 \to \dots \to C_k \to C_1 with k≥2k \ge 2 distinct components would give paths both ways between all vertices of all CiC_i (within each component by definition and between them via edges), so they would be one component. ■\blacksquare

∎

Do not confuse strongly connected components with connected components of the underlying undirected graph (ignoring direction): graph a→b→ca \to b \to c is connected and has three strongly connected components. Condensation solves the opening problem generally: even with cycles, compile modules in mutually dependent groups, topologically ordered.

Kosaraju: two searches and the transpose graph

For a component CC, let f(C)=max⁡v∈Cf[v]f(C) = \max_{v \in C} f[v] and d(C)=min⁡v∈Cd[v]d(C) = \min_{v \in C} d[v].

Proof

First case, d(C)<d(C′)d(C) < d(C'). Let xx be the first discovered vertex of CC. At time d[x]d[x] all vertices of CC and C′C' are white, with a white path from xx to each: within CC by strong connectivity, and to C′C' across edge u→vu \to v and within C′C'. By the white-path theorem, all descend from xx, so f[x]≥f[w]f[x] \ge f[w] for every w∈C∪C′w \in C \cup C', in particular f(C)=f[x]>f(C′)f(C) = f[x] > f(C').

Second case, d(C′)<d(C)d(C') < d(C). Let yy be the first discovered vertex of C′C'. At d[y]d[y], every C′C' is white and becomes a descendant of yy. From yy no vertex of CC is reachable: otherwise, since CC reaches C′C', they would be the same component. Thus all vertices of CC are white at d[y]d[y] and not descendants of yy, so they are discovered after yy finishes. Thus f(C′)=f[y]<d(C)≤f(C)f(C') = f[y] < d(C) \le f(C). ■\blacksquare

∎

The lemma says ordering components by decreasing f(C)f(C) gives a topological order of the condensation: if an edge goes from CC to C′C', the greater ff is CC. (Vertices ordered by decreasing ff are not grouped by component, but the first vertex of each marks f(C)f(C).) Kosaraju’s algorithm (also published independently by Sharir) exploits this:

  1. DFS on GG to obtain finish times.
  2. Build the transpose graph GTG^{\mathsf T} (same edges reversed). It has the same strongly connected components as GG.
  3. DFS on GTG^{\mathsf T}, choosing roots by decreasing ff (those of GG). Each resulting forest tree is one component.
Proof

Induct on trees, assuming each earlier tree was a complete component, so components are entirely visited or entirely unvisited. Let xx be the unvisited vertex with greatest ff and C=C(x)C = C(x) its component: because CC is entirely unvisited and xx has greatest ff among unvisited vertices, f[x]=f(C)f[x] = f(C). Inside CC everything is reachable from xx in GTG^{\mathsf T}, so the tree contains CC. It remains to show it cannot leave. An edge of GTG^{\mathsf T} from a vertex of CC to one in component C′≠CC' \ne C is an edge of GG from C′C' to CC, and the lemma gives f(C′)>f(C)f(C') > f(C); but CC contains the unvisited vertex of greatest ff, so C′C' must already be visited, and search does not enter visited vertices. Cost is two DFS traversals plus transpose construction (counting sort). ■\blacksquare

∎

An immediate consequence of the lemma, to prove in an exercise, is that the vertex of greatest ff belongs to a source component of the condensation (no incoming edge from another component). Kosaraju is easy to remember and prove. Its cost is the transpose and a second pass; Tarjan solves it in one.

Tarjan: one pass with a stack

Tarjan (1972) computes components in one DFS without a transpose, using two numbers per vertex and an explicit stack of discovered vertices not yet assigned to a component.

  • idx[v]\mathrm{idx}[v]: discovery order (0,1,2,…0, 1, 2, \dots).
  • low[v]\mathrm{low}[v]: the smallest index reachable from vv‘s subtree following tree edges and at most one edge to a vertex still on the stack.

When examining edge v→wv \to w: if ww is new, descend and on return low[v]←min⁡(low[v],low[w])\mathrm{low}[v] \gets \min(\mathrm{low}[v], \mathrm{low}[w]); if ww is still on the stack, low[v]←min⁡(low[v],idx[w])\mathrm{low}[v] \gets \min(\mathrm{low}[v], \mathrm{idx}[w]); if ww has left the stack, ignore it. When vv exhausts its edges and low[v]=idx[v]\mathrm{low}[v] = \mathrm{idx}[v], vv is a component root: pop through vv inclusive; the popped vertices are the component.

InteractiveTarjan step by step
a0/0b1/0c2/2d3/2e7/0f6/5g5/5h4/4Tarjan stack (bottom left, top right)Empty stack. Components in closing order:#1 {h} #2 {f, g} #3 {c, d} #4 {a, b, e}
step 27 of 27
Graph
Neighbor order
View
Closed components4 of 4
Current vertex·
Stack (bottom to top)empty
Done: 4 components. They were popped in reverse topological order: the first is a sink in the condensation graph.
Initially the algorithm has finished on an eight-vertex graph with four components. Press ⏮ then ▶, or step forward. Each vertex shows index/low: low below index (orange) means an older stack entry is reachable. Watch the stack below and wait for b to return from e with low 0: b and e do not close a component because low ≠ index; only when a finishes with low = index = 0 are all three popped. Components emerge in order #1 = {h}, #2 = {f, g}, #3 = {c, d}, #4 = {a, b, e}: the first is a sink. At the end press ‘Condensation’: the contracted graph is a DAG and descending numbers #4 → #3 → #2 → #1 give a topological order. Switch to ‘Two rings and a bridge’ or ‘No cycles’, or edit edges with two clicks, and check that low = index occurs only at roots.
Proof

Let ρ(w)\rho(w) be the first discovered vertex of ww‘s component. By the white-path theorem all vertices of ρ(w)\rho(w)‘s component descend from it (at its discovery they are white and connected to ρ\rho by paths within the component). Induct over successive finish events, assuming all earlier pops were complete components. This implies invariant (I): a discovered vertex is on the stack if and only if ρ(w)\rho(w) has not yet finished.

(⇒\Rightarrow) Show v=ρ(v)v = \rho(v) implies low[v]=idx[v]\mathrm{low}[v] = \mathrm{idx}[v]. If low[v]<idx[v]\mathrm{low}[v] < \mathrm{idx}[v], there would be an edge y→xy \to x with yy in vv‘s subtree, xx on the stack then, and idx[x]<idx[v]\mathrm{idx}[x] < \mathrm{idx}[v]. By (I), ρ(x)\rho(x) was open, hence gray, an ancestor of yy; since idx[ρ(x)]≤idx[x]<idx[v]\mathrm{idx}[\rho(x)] \le \mathrm{idx}[x] < \mathrm{idx}[v] it is a proper ancestor of vv. Then ρ(x)\rho(x) reaches vv by the tree, vv reaches yy by the tree, y→xy \to x, and xx reaches ρ(x)\rho(x) within its component: vv belongs to ρ(x)\rho(x)‘s component and was discovered before vv, contradicting v=ρ(v)v = \rho(v).

(⇐\Leftarrow) Show low[v]=idx[v]\mathrm{low}[v] = \mathrm{idx}[v] implies v=ρ(v)v = \rho(v). If v≠ρ(v)v \ne \rho(v), r=ρ(v)r = \rho(v) is an ancestor of vv and remains open. Let y→xy \to x be the first edge on a path from vv to rr within the component that leaves vv‘s subtree (it exists because rr is outside it). When examined, xx had already been discovered (if white, it would have become a descendant of yy, hence of vv), and since it is not a descendant of vv and was discovered before vv finished, idx[x]<idx[v]\mathrm{idx}[x] < \mathrm{idx}[v]. Also xx belongs to rr‘s still-open component, so by (I) it was on the stack. Examining y→xy \to x gives low[y]≤idx[x]<idx[v]\mathrm{low}[y] \le \mathrm{idx}[x] < \mathrm{idx}[v], and that value propagates up the tree to vv: low[v]<idx[v]\mathrm{low}[v] < \mathrm{idx}[v].

It remains to see what is popped when root v=ρ(v)v = \rho(v) finishes. All of vv‘s component is on the stack above vv (descendants discovered later, and not yet popped by (I)). A vertex ww above vv on the stack descends from vv and its ρ(w)\rho(w) remains open: it is vv or a proper ancestor of vv; in the latter case ρ(w)\rho(w) reaches vv by the tree, vv reaches ww, and ww reaches ρ(w)\rho(w), so vv would belong to ρ(w)\rho(w)‘s component with ρ(w)≠v\rho(w) \ne v, a contradiction. Thus exactly vv‘s component is popped.

Components emerge in reverse topological order: if an edge goes from CC to C′C', Kosaraju’s lemma gives f(C′)<f(C)f(C') < f(C), so C′C'‘s root finishes and is popped before CC‘s. Each vertex is pushed and popped once and each edge examined once: Θ(n+m)\Theta(n + m). ■\blacksquare

∎

Two observations. First, what closes a component is not the low\mathrm{low} value of an arbitrary vertex but its root: other component vertices have low<idx\mathrm{low} < \mathrm{idx}, as shown for bb and ee. Second, output numbering already gives a topological order of the condensation (read backward), for free: 2-SAT below uses this, avoiding construction and sorting of the condensation.

Recursion: why iteration is needed

Recursive DFS uses one call per vertex of the active path. On a path of one hundred thousand vertices, the search descends one hundred thousand levels; recursion that deep exceeds Python’s limit (1000 calls by default, and raising it with sys.setrecursionlimit can crash the interpreter by overflowing the C stack). The solution already seen above is an explicit stack with, for every open vertex, a pointer to the next edge to inspect. With CSR the pointer is an integer traversing indices[indptr[u]:indptr[u+1]]. The iterative version performs exactly the same operations and is implemented in the lab.

2-SAT with strongly connected components

A 2-SAT formula is a conjunction of two-literal clauses (ℓ1∨ℓ2)(\ell_1 \lor \ell_2) (2-SAT). Each clause is equivalent to two implications, ¬ℓ1⇒ℓ2\lnot \ell_1 \Rightarrow \ell_2 and ¬ℓ2⇒ℓ1\lnot \ell_2 \Rightarrow \ell_1. The implication graph has one vertex per literal (thus 2k2k vertices for kk variables) and one edge per implication. It is skew-symmetric under negation (not to be confused with an antisymmetric relation): there is an edge ℓ→ℓ′\ell \to \ell' if and only if there is ¬ℓ′→¬ℓ\lnot \ell' \to \lnot \ell.

Proof

If xx and ¬x\lnot x share a component, implication paths x⇒⋯⇒¬xx \Rightarrow \dots \Rightarrow \lnot x and ¬x⇒⋯⇒x\lnot x \Rightarrow \dots \Rightarrow x exist, and no value of xx satisfies them all. Conversely, assume no variable shares a component with its negation and let pos(ℓ)\mathrm{pos}(\ell) be the position of ℓ\ell‘s component in a condensation topological order. Since pos(x)≠pos(¬x)\mathrm{pos}(x) \ne \mathrm{pos}(\lnot x), the rule “ℓ\ell is true iff pos(ℓ)>pos(¬ℓ)\mathrm{pos}(\ell) > \mathrm{pos}(\lnot \ell)” consistently assigns each variable. Suppose it violates a clause, meaning an implication ℓ→ℓ′\ell \to \ell' has ℓ\ell true and ℓ′\ell' false. Then pos(¬ℓ)<pos(ℓ)\mathrm{pos}(\lnot \ell) < \mathrm{pos}(\ell) and pos(ℓ′)<pos(¬ℓ′)\mathrm{pos}(\ell') < \mathrm{pos}(\lnot \ell'). Since ℓ→ℓ′\ell \to \ell' is an edge, pos(ℓ)≤pos(ℓ′)\mathrm{pos}(\ell) \le \mathrm{pos}(\ell'), and by symmetry ¬ℓ′→¬ℓ\lnot \ell' \to \lnot \ell gives pos(¬ℓ′)≤pos(¬ℓ)\mathrm{pos}(\lnot \ell') \le \mathrm{pos}(\lnot \ell). Chaining them gives pos(¬ℓ)<pos(ℓ)≤pos(ℓ′)<pos(¬ℓ′)≤pos(¬ℓ)\mathrm{pos}(\lnot \ell) < \mathrm{pos}(\ell) \le \mathrm{pos}(\ell') < \mathrm{pos}(\lnot \ell') \le \mathrm{pos}(\lnot \ell), absurd. ■\blacksquare

∎

With Tarjan numbering, already reverse topological order, the rule needs no extra computation: the variable is true if its literal’s component number is smaller than its negation’s.

Module dependencies

Everything comes together in the opening problem. The figure uses eleven modules of a fictional project: edge u→vu \to v means “uu must be ready before vv”, i.e. vv depends on uu.

InteractiveCycles in a dependency graph
enoughcfgconfiglogloggingutlutilsdbdbcchcachemodmodelsschschemasautauthapiapiclicliappapp
Project
Statecyclic
Components with cycles1
Kahn places5 of 11
Blocked6 of 11
One edge sufficesapi → models
Shortest cycle of {models, schemas, auth, api}: models → schemas → api → models.
Initially the project has a circular import among models, schemas and api. Kahn places only 5 of 11 modules and stalls on the other 6 (the cycle and its dependents); the strongly connected component is {models, schemas, auth, api} and the shortest cycle, the certificate, is red. One edge marked ‘suffices’ breaks all cycles: api → models. Click it to remove it; the graph becomes ‘acyclic’ with a build order and 8 waves. Enable ‘Level layout’ to see build levels as columns. Try ‘Two cycles’: now two components have cycles and no single edge suffices. Draw your own dependencies with two clicks.

The shortest cycle is shown to the developer. It has the fewest edges among cycles passing through a component vertex: find it with BFS from each component vertex (distance back to the source), costing O(s(s+ms))\bigO(s (s + m_s)) for a component with ss vertices and msm_s internal edges. Finding the smallest set of edges whose removal breaks all cycles (a feedback arc set) is NP-hard in general; the figure’s check that one edge suffices is polynomial, testing each edge with an acyclicity test.

Bridges, articulation points and biconnected components

For undirected graphs, a robustness question is which elements disconnect the graph when removed.

Testing each element separately (remove it and count components) would cost O((n+m)2)\bigO((n + m)^2). DFS solves it in one pass because, in an undirected graph, everything that is not a tree edge is a back edge to an ancestor. Let low(v)\mathrm{low}(v) be the smallest d[w]d[w] reachable from vv‘s subtree with one back edge:

low(v)=min⁡({d[v]}∪{ d[w]:(x,w) es de retroceso con x en el subaˊrbol de v }).\mathrm{low}(v) = \min\bigl(\{d[v]\} \cup \{\, d[w] : (x, w) \text{ es de retroceso con } x \text{ en el subárbol de } v \,\}\bigr).

Compute it as each vertex finishes, as in Tarjan, as the minimum of three things: its own d[v]d[v], the d[w]d[w] values of back edges leaving vv, and the low(c)\mathrm{low}(c) values of its tree children cc. One detail is essential: the tree edge used to reach vv does not count as a back edge to its parent (otherwise no edge would be a bridge). Identify it by edge ID, not endpoint, which also handles parallel edges correctly.

Proof

Everything leaving cc‘s subtree is tree edge (p,c)(p, c) or a back edge to an ancestor of cc (there are no cross edges: an edge between cc‘s subtree and an outside vertex connects ancestor to descendant).

(1) A back edge closes a cycle with the tree path, so removing it disconnects nothing. For (p,c)(p, c): the only vertices with d<d[c]d < d[c] on cc‘s ancestor path are pp and those above it, with d≤d[p]d \le d[p]. If low(c)≤d[p]\mathrm{low}(c) \le d[p] there is a back edge from cc‘s subtree to pp or above, and the subtree remains connected to the rest without edge (p,c)(p, c). If low(c)>d[p]\mathrm{low}(c) > d[p], no such back edge exists and (p,c)(p, c) is the only edge between cc‘s subtree and the rest: removing it disconnects it.

(2) If a child cc satisfies low(c)≥d[v]\mathrm{low}(c) \ge d[v], cc‘s subtree connects outside only through vv (its back edges reach at most vv), and removing vv isolates it from p(v)p(v), which exists because vv is not the root. If all children satisfy low(c)<d[v]\mathrm{low}(c) < d[v], each child subtree has a back edge to a proper ancestor of vv; the tree without vv‘s subtree remains connected (it contains the root), and every child subtree joins it, so G−vG - v is connected.

(3) Without the root, its children’s subtrees have no edges between them (they would be cross edges), so at least two remain separate; one forms a single connected block. ■\blacksquare

∎

Biconnected components emerge from the same traversal with an edge stack: when child cc of vv finishes with low(c)≥d[v]\mathrm{low}(c) \ge d[v], pop edges through (v,c)(v, c) and those form a block. Articulation points are vertices belonging to multiple blocks. Removing all bridges leaves 2-edge-connected components, which, contracted to one vertex each, form a tree if the graph is connected (the bridge tree).

InteractiveBridges and articulation points with low
bridgebridgebridgea1/1b2/1c3/1d4/4e5/4f6/4g7/4h8/8i9/9
step 26 of 26
Graph
Graph click
  • tree edge
  • back edge
  • bridge
  • articulation point
Connected components1
Bridges detected3
Articulation points4
Done: 3 bridge(s) and 4 articulation point(s).
Initial state (‘Two communities’): a triangle, a square and a tail joined by edges, with search finished. Press ⏮ then ▶ to repeat: each vertex shows d/low, and when a child finishes with low > d[parent] its edge turns red (bridge); with low ≥ d[parent] the parent receives a ring (articulation point), except the root receives it only with at least two children. Finally there are 3 bridges (c-d, g-h and h-i) and 4 articulation points (c, d, g and h). Switch to ‘Test by removal’ and click an edge or vertex: brute-force component counting always agrees with low. Try ‘One ring’: the ring has no bridges, only tail (i-e) does, and e is the only articulation point. In ‘A tree’ all edges are bridges and the 5 internal vertices are articulation points.

Implementation from scratch

Five cells build a small CSR-based library, all iterative, each part checked against networkx on random graphs. They share a session: later cells use earlier definitions.

First cell: CSR using counting sort, BFS with deque, and iterative DFS with a pointer per vertex, computing dd, ff, parent, finish order and edge classification. The parenthesis theorem is checked on each result and the list.pop(0) queue error measured.

[ ]CSR, BFS and DFS with times and edge classificationBrowser
import random
import time
from collections import deque

import networkx as nx
import numpy as np


class CSR:
    """Grafo dirigido en formato CSR: indptr (n + 1 posiciones) e indices (m posiciones)."""

    def __init__(self, n, aristas):
        indptr = [0] * (n + 1)
        for u, _ in aristas:                  # 1) grados de salida, desplazados una posición
            indptr[u + 1] += 1
        for i in range(n):                    # 2) suma de prefijos: indptr[u] es dónde empieza la fila u
            indptr[i + 1] += indptr[i]
        siguiente = indptr[:-1]               # una copia: la próxima posición libre de cada fila
        indices = [0] * len(aristas)
        for u, v in aristas:                  # 3) colocación: cada arista va a su hueco
            indices[siguiente[u]] = v
            siguiente[u] += 1
        self.n, self.m = n, len(aristas)
        self.indptr, self.indices = indptr, indices

    def vecinos(self, u):
        return self.indices[self.indptr[u]:self.indptr[u + 1]]

    def traspuesto(self):
        return CSR(self.n, [(v, u) for u in range(self.n) for v in self.vecinos(u)])

    def bytes_numpy(self):
        """Lo que ocuparía con índices de 32 bits en arrays de NumPy."""
        return np.array(self.indptr, dtype=np.int32).nbytes + np.array(self.indices, dtype=np.int32).nbytes


def bfs(g, origen):
    """Distancias (en aristas) desde el origen; -1 si no es alcanzable. O(n + m)."""
    ip, ix = g.indptr, g.indices
    dist = [-1] * g.n
    dist[origen] = 0
    cola = deque([origen])                    # deque: popleft en O(1); list.pop(0) sería O(n)
    while cola:
        u = cola.popleft()
        for k in range(ip[u], ip[u + 1]):
            v = ix[k]
            if dist[v] < 0:
                dist[v] = dist[u] + 1
                cola.append(v)
    return dist


def dfs(g):
    """DFS iterativa con tiempos d y f, padres, orden de finalización y clasificación de aristas."""
    n, ip, ix = g.n, g.indptr, g.indices
    d, f, padre = [0] * n, [0] * n, [-1] * n
    siguiente = ip[:-1]                       # puntero a la próxima arista de cada vértice
    tipos = {"arbol": 0, "retroceso": 0, "avance": 0, "cruzada": 0}
    fin, reloj = [], 0
    for s in range(n):
        if d[s]:
            continue
        reloj += 1
        d[s] = reloj
        pila = [s]
        while pila:
            u = pila[-1]
            if siguiente[u] < ip[u + 1]:
                v = ix[siguiente[u]]
                siguiente[u] += 1
                if not d[v]:                  # blanco
                    tipos["arbol"] += 1
                    padre[v] = u
                    reloj += 1
                    d[v] = reloj
                    pila.append(v)
                elif not f[v]:                # gris: sigue abierto
                    tipos["retroceso"] += 1
                elif d[u] < d[v]:             # negro y descubierto después
                    tipos["avance"] += 1
                else:                         # negro y descubierto antes
                    tipos["cruzada"] += 1
            else:
                reloj += 1
                f[u] = reloj
                fin.append(u)
                pila.pop()
    return d, f, padre, fin, tipos


def aleatorio(n, m, semilla):
    r = random.Random(semilla)
    return [(r.randrange(n), r.randrange(n)) for _ in range(m)]


# el ejemplo de la figura: u v w x y z = 0..5
ej = CSR(6, [(0, 1), (0, 3), (1, 4), (2, 4), (2, 5), (3, 1), (4, 3), (5, 5)])
d, f, padre, fin, tipos = dfs(ej)
print("intervalos [d, f]:", {"uvwxyz"[v]: (d[v], f[v]) for v in range(6)})
print("aristas por tipo:", tipos)


def parentesis_ok(d, f):
    """Teorema del paréntesis: dos intervalos son disjuntos o uno contiene al otro, nunca se cruzan."""
    n = len(d)
    for u in range(n):
        for v in range(u + 1, n):
            disjuntos = f[u] < d[v] or f[v] < d[u]
            anidados = (d[u] < d[v] < f[v] < f[u]) or (d[v] < d[u] < f[u] < f[v])
            if not (disjuntos or anidados):
                return False
    return True


# contraste con networkx: orden de descubrimiento, orden de finalización y distancias de BFS
desacuerdos = 0
for semilla in range(60):
    n = random.Random(semilla).randint(2, 40)
    aristas = list(dict.fromkeys(aleatorio(n, random.Random(semilla + 1000).randint(0, 3 * n), semilla)))
    g = CSR(n, aristas)
    d, f, padre, fin, tipos = dfs(g)
    G = nx.DiGraph()
    G.add_nodes_from(range(n))
    G.add_edges_from(aristas)
    ok = sorted(range(n), key=lambda v: d[v]) == list(nx.dfs_preorder_nodes(G))
    ok = ok and fin == list(nx.dfs_postorder_nodes(G)) and parentesis_ok(d, f)
    dist, ref = bfs(g, 0), nx.single_source_shortest_path_length(G, 0)
    ok = ok and all(dist[v] == ref.get(v, -1) for v in range(n))
    desacuerdos += not ok
print("grafos aleatorios con algún desacuerdo frente a networkx:", desacuerdos, "de 60")


def bfs_lista(g, origen):
    """BFS con list.pop(0): el error típico."""
    ip, ix = g.indptr, g.indices
    dist = [-1] * g.n
    dist[origen] = 0
    cola = [origen]
    while cola:
        u = cola.pop(0)                       # O(longitud de la cola)
        for k in range(ip[u], ip[u + 1]):
            v = ix[k]
            if dist[v] < 0:
                dist[v] = dist[u] + 1
                cola.append(v)
    return dist


for n in (10000, 20000, 40000):
    estrella = CSR(n, [(0, v) for v in range(1, n)])  # el origen tiene n - 1 vecinos: la cola llega a medir n - 1
    t0 = time.perf_counter(); bfs(estrella, 0); t1 = time.perf_counter(); bfs_lista(estrella, 0); t2 = time.perf_counter()
    print(f"n = {n:6d}: deque {1000 * (t1 - t0):7.1f} ms   list.pop(0) {1000 * (t2 - t1):8.1f} ms")

The figure example yields the intervals and classifications seen above (4 tree, 2 back, 1 forward and 1 cross edge). Discovery and finish orders match networkx across random graphs, the parenthesis theorem holds throughout, and BFS distances match too. The final test quantifies the queue error: in a star the queue reaches n−1n - 1 elements and each pop(0) shifts all of them.

Second cell: both topological sorting algorithms, their certificates and verifiers, on random graphs with and without cycles.

[ ]Topological order with certificates: Kahn and DFSBrowser
def kahn(g):
    """Orden topológico por grados de entrada. Devuelve (orden, grado_restante): hay ciclo si len(orden) < n."""
    n, ip, ix = g.n, g.indptr, g.indices
    grado = [0] * n
    for v in ix:
        grado[v] += 1
    cola = deque(v for v in range(n) if grado[v] == 0)
    orden = []
    while cola:
        u = cola.popleft()
        orden.append(u)
        for k in range(ip[u], ip[u + 1]):
            v = ix[k]
            grado[v] -= 1
            if grado[v] == 0:
                cola.append(v)
    return orden, grado


def ciclo_de_los_restantes(g, orden):
    """Certificado de ciclo a partir de lo que Kahn no pudo colocar: todo vértice restante tiene un predecesor restante."""
    resto = set(range(g.n)) - set(orden)
    gt = g.traspuesto()
    v = next(iter(resto))
    visto, camino = {}, []
    while v not in visto:                     # caminar hacia atrás: tarde o temprano se repite un vértice
        visto[v] = len(camino)
        camino.append(v)
        v = next(w for w in gt.vecinos(v) if w in resto)
    return camino[visto[v]:][::-1]            # el ciclo, ya en el sentido de las aristas


def topologico_dfs(g):
    """Orden por tiempo de finalización decreciente; si la DFS ve una arista de retroceso devuelve su ciclo."""
    n, ip, ix = g.n, g.indptr, g.indices
    color, padre, siguiente, fin = [0] * n, [-1] * n, ip[:-1], []
    for s in range(n):
        if color[s]:
            continue
        color[s] = 1
        pila = [s]
        while pila:
            u = pila[-1]
            if siguiente[u] < ip[u + 1]:
                v = ix[siguiente[u]]
                siguiente[u] += 1
                if color[v] == 0:
                    color[v], padre[v] = 1, u
                    pila.append(v)
                elif color[v] == 1:           # arista de retroceso u -> v: el camino de árbol v ... u la cierra
                    ciclo, x = [u], u
                    while x != v:
                        x = padre[x]
                        ciclo.append(x)
                    return "ciclo", ciclo[::-1]
            else:
                color[u] = 2
                fin.append(u)
                pila.pop()
    return "orden", fin[::-1]


def verificar_orden(g, orden):
    """Un certificado de orden se comprueba en O(n + m): cada arista debe ir hacia delante."""
    pos = {v: i for i, v in enumerate(orden)}
    return len(pos) == g.n and all(pos[u] < pos[v] for u in range(g.n) for v in g.vecinos(u))


def verificar_ciclo(g, ciclo):
    """Un certificado de ciclo se comprueba en O(longitud): cada paso debe ser una arista."""
    return len(ciclo) >= 1 and all(ciclo[(i + 1) % len(ciclo)] in g.vecinos(c) for i, c in enumerate(ciclo))


rnd = random.Random(7)
resumen = {"acíclicos": 0, "cíclicos": 0}
for _ in range(200):
    n = rnd.randint(2, 30)
    perm = list(range(n))
    rnd.shuffle(perm)
    aristas = [tuple(sorted((rnd.randrange(n), rnd.randrange(n)))) for _ in range(rnd.randint(0, 2 * n))]
    aristas = [(perm[a], perm[b]) for a, b in aristas if a != b]      # un DAG con los vértices barajados
    if rnd.random() < 0.5 and aristas:
        aristas.append((rnd.randrange(n), rnd.randrange(n)))          # con probabilidad 1/2, una arista que puede cerrar un ciclo
    g = CSR(n, aristas)
    G = nx.DiGraph(aristas)
    G.add_nodes_from(range(n))
    orden, _ = kahn(g)
    tipo, cert = topologico_dfs(g)
    if nx.is_directed_acyclic_graph(G):
        resumen["acíclicos"] += 1
        assert len(orden) == n and verificar_orden(g, orden)
        assert tipo == "orden" and verificar_orden(g, cert)
    else:
        resumen["cíclicos"] += 1
        assert len(orden) < n and verificar_ciclo(g, ciclo_de_los_restantes(g, orden))
        assert tipo == "ciclo" and verificar_ciclo(g, cert)
print("200 grafos aleatorios:", resumen, "- todos los certificados verifican")

# el proyecto de la figura, con y sin el import circular models <- api
modulos = ["config", "logging", "utils", "db", "cache", "models", "schemas", "auth", "api", "cli", "app"]
nombres = {m: i for i, m in enumerate(modulos)}
dep = [("config", "logging"), ("config", "db"), ("config", "cache"), ("logging", "db"), ("utils", "db"), ("utils", "cache"),
       ("utils", "schemas"), ("db", "models"), ("models", "schemas"), ("models", "auth"), ("cache", "auth"), ("schemas", "api"),
       ("auth", "api"), ("api", "cli"), ("api", "app"), ("cli", "app")]
aristas = [(nombres[a], nombres[b]) for a, b in dep]
orden, _ = kahn(CSR(len(modulos), aristas))
print("orden de compilación:", " -> ".join(modulos[v] for v in orden))
g2 = CSR(len(modulos), aristas + [(nombres["api"], nombres["models"])])
orden2, _ = kahn(g2)
ciclo = ciclo_de_los_restantes(g2, orden2)
print("con el import circular, Kahn coloca", len(orden2), "de", len(modulos), "y el certificado es:", " -> ".join(modulos[v] for v in ciclo + ciclo[:1]))
tipo, cert = topologico_dfs(g2)
print("la DFS encuentra otro ciclo:", " -> ".join(modulos[v] for v in cert + cert[:1]))

Both algorithms agree with networkx about cycle existence, and both certificates pass verification. In the project figure Kahn places 5 of 11 modules and stalls, and both methods return the same three-module cycle (from a different starting point). But it is not the only one: the component also contains the cycle models, auth, api. Certificates are not unique; each algorithm gives the first it finds.

Third cell: minimal autograd with topological order in action. The gradient uses DFS reverse postorder and is compared with finite differences and preorder, which is not topological.

[ ]Minimal autograd and topological order of the backward passBrowser
import math


class Valor:
    """Un escalar con historia: sabe de qué operandos viene y cómo reparte el gradiente entre ellos."""

    def __init__(self, dato, operandos=()):
        self.dato, self.grad, self.operandos = dato, 0.0, operandos
        self.repartir = lambda: None

    def __add__(self, o):
        r = Valor(self.dato + o.dato, (self, o))
        def repartir():
            self.grad += r.grad
            o.grad += r.grad
        r.repartir = repartir
        return r

    def __mul__(self, o):
        r = Valor(self.dato * o.dato, (self, o))
        def repartir():
            self.grad += o.dato * r.grad
            o.grad += self.dato * r.grad
        r.repartir = repartir
        return r

    def tanh(self):
        t = math.tanh(self.dato)
        r = Valor(t, (self,))
        def repartir():
            self.grad += (1 - t * t) * r.grad
        r.repartir = repartir
        return r

    def recorrido(self):
        """DFS iterativa desde este nodo hacia sus operandos. Devuelve (preorden, postorden)."""
        visto, pre, post, pila = {id(self)}, [self], [], [(self, 0)]
        while pila:
            nodo, i = pila.pop()
            if i < len(nodo.operandos):
                pila.append((nodo, i + 1))
                h = nodo.operandos[i]
                if id(h) not in visto:
                    visto.add(id(h))
                    pre.append(h)
                    pila.append((h, 0))
            else:
                post.append(nodo)             # todos sus operandos ya han terminado: van antes en el postorden
        return pre, post

    def backward(self, orden="topologico"):
        pre, post = self.recorrido()
        secuencia = post[::-1] if orden == "topologico" else pre    # reverso del postorden, o el preorden (incorrecto)
        self.grad = 1.0
        for nodo in secuencia:
            nodo.repartir()


def funcion(a, b, c):
    s = a * b                                 # s lo usan dos nodos distintos: un rombo en el grafo
    u = s + c
    w = s * c
    return (u * w).tanh()


x0 = (0.7, -1.3, 0.4)


def gradientes(orden):
    a, b, c = (Valor(t) for t in x0)
    funcion(a, b, c).backward(orden)
    return [a.grad, b.grad, c.grad]


h = 1e-6
numerico = []
for i in range(3):
    mas, menos = list(x0), list(x0)
    mas[i] += h
    menos[i] -= h
    numerico.append((funcion(*[Valor(t) for t in mas]).dato - funcion(*[Valor(t) for t in menos]).dato) / (2 * h))
print("diferencias finitas   :", np.round(numerico, 6))
print("orden topológico (f)  :", np.round(gradientes("topologico"), 6))
print("preorden (d)          :", np.round(gradientes("preorden"), 6))

With reverse postorder all three gradients match finite differences. With preorder (here yy, uwu w, uu, ss, aa, bb, cc, ww), gradients of aa and bb are wrong: node s=abs = a b is used by uu and ww, and preorder visits ss immediately after uu, before ww has sent its contribution. cc’s gradient is correct, but not because the order is valid: cc is a leaf propagating nothing, and the two nodes sending it gradients, uu and ww, each have one consumer, so already have their full gradients when propagating.

Fourth cell: iterative Tarjan, Kosaraju and 2-SAT, checked against networkx and scipy, and failure of the recursive version.

[ ]Iterative Tarjan, Kosaraju and 2-SATBrowser
import sys
from itertools import product

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components


def tarjan(g):
    """Componentes fuertemente conexas, iterativo. comp[v] numera las componentes en el orden en que se cierran:
    toda arista u -> v cumple comp[u] >= comp[v] (la primera componente es un sumidero)."""
    n, ip, ix = g.n, g.indptr, g.indices
    idx, low, comp = [-1] * n, [0] * n, [-1] * n
    siguiente, pila, llamadas = ip[:-1], [], []
    contador = nc = 0
    for s in range(n):
        if idx[s] >= 0:
            continue
        idx[s] = low[s] = contador
        contador += 1
        pila.append(s)
        llamadas.append(s)
        while llamadas:
            u = llamadas[-1]
            if siguiente[u] < ip[u + 1]:
                v = ix[siguiente[u]]
                siguiente[u] += 1
                if idx[v] < 0:                # vértice nuevo: arista de árbol
                    idx[v] = low[v] = contador
                    contador += 1
                    pila.append(v)
                    llamadas.append(v)
                elif comp[v] < 0 and idx[v] < low[u]:   # sigue en la pila: puede volver a él
                    low[u] = idx[v]
            else:
                llamadas.pop()
                if low[u] == idx[u]:          # u es la raíz de una componente: se desapila hasta u
                    while True:
                        w = pila.pop()
                        comp[w] = nc
                        if w == u:
                            break
                    nc += 1
                if llamadas and low[u] < low[llamadas[-1]]:
                    low[llamadas[-1]] = low[u]
    return comp, nc


def tarjan_recursivo(g):
    """La versión de manual, recursiva. Solo para ver cómo falla."""
    n, ip, ix = g.n, g.indptr, g.indices
    idx, low, comp, pila = [-1] * n, [0] * n, [-1] * n, []
    estado = {"c": 0, "nc": 0}

    def visitar(u):
        idx[u] = low[u] = estado["c"]
        estado["c"] += 1
        pila.append(u)
        for k in range(ip[u], ip[u + 1]):
            v = ix[k]
            if idx[v] < 0:
                visitar(v)
                low[u] = min(low[u], low[v])
            elif comp[v] < 0:
                low[u] = min(low[u], idx[v])
        if low[u] == idx[u]:
            while True:
                w = pila.pop()
                comp[w] = estado["nc"]
                if w == u:
                    break
            estado["nc"] += 1

    for s in range(n):
        if idx[s] < 0:
            visitar(s)
    return comp, estado["nc"]


def kosaraju(g):
    """Dos DFS: una sobre G para el orden de finalización y otra sobre el traspuesto, en orden de f decreciente."""
    _, _, _, fin, _ = dfs(g)
    gt = g.traspuesto()
    comp, nc = [-1] * g.n, 0
    for s in reversed(fin):
        if comp[s] >= 0:
            continue
        comp[s] = nc
        pila = [s]
        while pila:
            u = pila.pop()
            for v in gt.vecinos(u):
                if comp[v] < 0:
                    comp[v] = nc
                    pila.append(v)
        nc += 1
    return comp, nc


def particion(comp):
    grupos = {}
    for v, c in enumerate(comp):
        grupos.setdefault(c, set()).add(v)
    return {frozenset(s) for s in grupos.values()}


# el ejemplo de la figura: a..h
g = CSR(8, [(0, 1), (1, 2), (1, 4), (1, 5), (2, 3), (2, 6), (3, 2), (3, 7), (4, 0), (4, 5), (5, 6), (6, 5), (6, 7), (7, 7)])
comp, nc = tarjan(g)
print("componentes de Tarjan, en orden de cierre:", [["abcdefgh"[v] for v in range(8) if comp[v] == c] for c in range(nc)])

# contraste con networkx, scipy y Kosaraju
rnd = random.Random(3)
desacuerdos = 0
for _ in range(300):
    n = rnd.randint(1, 40)
    aristas = [(rnd.randrange(n), rnd.randrange(n)) for _ in range(rnd.randint(0, 2 * n))]
    g = CSR(n, aristas)
    G = nx.DiGraph(aristas)
    G.add_nodes_from(range(n))
    ref = {frozenset(c) for c in nx.strongly_connected_components(G)}
    comp_t, _ = tarjan(g)
    comp_k, _ = kosaraju(g)
    M = csr_matrix((np.ones(len(aristas)), ([a for a, _ in aristas], [b for _, b in aristas])), shape=(n, n))
    _, lab_s = connected_components(M, directed=True, connection="strong")
    ok = particion(comp_t) == ref and particion(comp_k) == ref and particion(list(lab_s)) == ref
    ok = ok and all(comp_t[u] >= comp_t[v] for u, v in aristas)    # Tarjan: orden topológico inverso
    ok = ok and all(comp_k[u] <= comp_k[v] for u, v in aristas)    # Kosaraju: orden topológico directo
    desacuerdos += not ok
print("desacuerdos entre Tarjan, Kosaraju, networkx y scipy en 300 grafos:", desacuerdos)

# recursión frente a iteración: un camino de miles de vértices
n = 20000
camino = CSR(n, [(i, i + 1) for i in range(n - 1)])
print("límite de recursión de este intérprete:", sys.getrecursionlimit())
try:
    tarjan_recursivo(camino)
    print("la versión recursiva terminó")
except RecursionError:
    print(f"versión recursiva con n = {n}: RecursionError")
print(f"versión iterativa con n = {n}: {tarjan(camino)[1]} componentes (cada vértice, la suya)")
anillo = CSR(n, [(i, (i + 1) % n) for i in range(n)])
print("anillo del mismo tamaño:", tarjan(anillo)[1], "componente")


def dos_sat(nvars, clausulas):
    """Cláusulas (a o b) con literales +i / -i (variables 1..nvars). Devuelve una asignación o None."""
    lit = lambda x: 2 * (abs(x) - 1) + (x < 0)          # 2i = x_i verdadera, 2i + 1 = x_i falsa
    neg = lambda l: l ^ 1
    aristas = []
    for a, b in clausulas:
        aristas += [(neg(lit(a)), lit(b)), (neg(lit(b)), lit(a))]   # la cláusula (a o b): no a implica b, y no b implica a
    comp, _ = tarjan(CSR(2 * nvars, aristas))
    if any(comp[2 * i] == comp[2 * i + 1] for i in range(nvars)):
        return None
    return [comp[2 * i] < comp[2 * i + 1] for i in range(nvars)]    # verdadera si su componente se cierra antes (va después en topológico)


def satisface(asig, clausulas):
    val = lambda x: asig[abs(x) - 1] == (x > 0)
    return all(val(a) or val(b) for a, b in clausulas)


rnd = random.Random(5)
resultados = {"sat": 0, "unsat": 0}
for _ in range(400):
    nv = rnd.randint(2, 7)
    cl = [(rnd.choice([-1, 1]) * rnd.randint(1, nv), rnd.choice([-1, 1]) * rnd.randint(1, nv)) for _ in range(rnd.randint(1, 3 * nv))]
    fuerza_bruta = any(satisface(a, cl) for a in product([False, True], repeat=nv))
    sol = dos_sat(nv, cl)
    assert (sol is not None) == fuerza_bruta
    if sol is not None:
        assert satisface(sol, cl)
    resultados["sat" if fuerza_bruta else "unsat"] += 1
print("2-SAT frente a fuerza bruta en 400 fórmulas:", resultados)

The four components emerge in the figure’s order. Tarjan, Kosaraju, networkx and scipy give the same partition on every random graph; Tarjan numbers components in reverse topological order and Kosaraju forward, as theory predicts. The recursive version fails on a twenty-thousand-vertex path, the iterative one does not, and component-based 2-SAT agrees with brute force on four hundred formulas using the proof’s assignment.

Fifth cell: bridges and articulation points in iterative DFS, with edge IDs, checked against networkx.

[ ]Bridges and articulation points using lowBrowser
def puentes_y_articulaciones(n, aristas):
    """Puentes (como índices de arista) y puntos de articulación de un grafo no dirigido, en una DFS iterativa.
    Las aristas llevan identificador para tratar bien las paralelas: solo se salta la arista por la que se llegó."""
    inc = [[] for _ in range(n)]
    for i, (u, v) in enumerate(aristas):
        inc[u].append((v, i))
        inc[v].append((u, i))
    d, low, padre_arista = [0] * n, [0] * n, [-1] * n
    siguiente = [0] * n
    puentes, articulacion, reloj = [], [False] * n, 0
    for s in range(n):
        if d[s]:
            continue
        reloj += 1
        d[s] = low[s] = reloj
        pila, hijos_raiz = [s], 0
        while pila:
            u = pila[-1]
            if siguiente[u] < len(inc[u]):
                v, i = inc[u][siguiente[u]]
                siguiente[u] += 1
                if i == padre_arista[u]:
                    continue                  # la arista por la que llegamos a u no cuenta como retroceso
                if not d[v]:                  # arista de árbol
                    reloj += 1
                    d[v] = low[v] = reloj
                    padre_arista[v] = i
                    pila.append(v)
                    if u == s:
                        hijos_raiz += 1
                else:                         # arista de retroceso (o su copia vista desde el ascendiente)
                    low[u] = min(low[u], d[v])
            else:
                pila.pop()
                if pila:
                    p = pila[-1]
                    low[p] = min(low[p], low[u])
                    if low[u] > d[p]:
                        puentes.append(padre_arista[u])
                    if p != s and low[u] >= d[p]:
                        articulacion[p] = True
        if hijos_raiz >= 2:
            articulacion[s] = True
    return puentes, [v for v in range(n) if articulacion[v]]


# el grafo de la figura: a..i
aristas = [(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 5), (5, 6), (6, 3), (6, 7), (7, 8)]
pu, ar = puentes_y_articulaciones(9, aristas)
print("puentes:", [("abcdefghi"[aristas[i][0]] + "-" + "abcdefghi"[aristas[i][1]]) for i in sorted(pu)],
      " articulaciones:", ["abcdefghi"[v] for v in ar])

# contraste con networkx, con aristas paralelas incluidas
rnd = random.Random(2)
desacuerdos = 0
for _ in range(400):
    n = rnd.randint(2, 30)
    aristas = []
    for _ in range(rnd.randint(0, int(1.4 * n))):
        a, b = rnd.randrange(n), rnd.randrange(n)
        if a != b:
            aristas.append((a, b))
    pu, ar = puentes_y_articulaciones(n, aristas)
    clave = lambda a, b: frozenset((a, b))
    veces = {}
    for a, b in aristas:
        veces[clave(a, b)] = veces.get(clave(a, b), 0) + 1
    mios = {clave(*aristas[i]) for i in pu}
    G = nx.Graph(aristas)
    G.add_nodes_from(range(n))
    ref = {clave(a, b) for a, b in nx.bridges(G) if veces[clave(a, b)] == 1}      # networkx ve el grafo simple; una arista doble no es puente
    desacuerdos += mios != ref or set(ar) != set(nx.articulation_points(G))
print("desacuerdos con networkx en 400 grafos (con aristas repetidas):", desacuerdos)

The cell reproduces the figure’s three bridges and four articulation points, and agrees with networkx on random graphs including parallel edges (a duplicated edge is not a bridge, so the comparison excludes those appearing more than once). Skipping only the arrival edge, not every edge to the parent, achieves this.

Sixth cell: actual cost. First, memory for a real graph of 2⋅1042 \cdot 10^4 vertices and 2⋅1052 \cdot 10^5 edges in Python lists and CSR; then time to build CSR, perform DFS and run Tarjan as edge count grows.

[ ]Actual memory and linear scalingBrowser
import struct

n, m = 20000, 200000
r = np.random.default_rng(0)
pares = list(zip(r.integers(0, n, m).tolist(), r.integers(0, n, m).tolist()))
listas = [[] for _ in range(n)]
for u, v in pares:
    listas[u].append(v)
en_listas = sys.getsizeof(listas) + sum(sys.getsizeof(l) for l in listas) + sum(sys.getsizeof(v) for l in listas for v in l)
en_csr = CSR(n, pares).bytes_numpy()
print(f"puntero de este intérprete: {8 * struct.calcsize('P')} bits")
print(f"listas de Python: {en_listas / 1e6:.2f} MB   CSR con int32: {en_csr / 1e6:.2f} MB   cociente: {en_listas / en_csr:.1f}")

print(f"\n{'aristas':>9}  {'CSR (ms)':>9}  {'DFS (ms)':>9}  {'Tarjan (ms)':>11}  {'µs por arista (Tarjan)':>23}")
for m in (25000, 50000, 100000, 200000):
    n = m // 4
    r = np.random.default_rng(m)
    pares = list(zip(r.integers(0, n, m).tolist(), r.integers(0, n, m).tolist()))
    t0 = time.perf_counter(); g = CSR(n, pares)
    t1 = time.perf_counter(); dfs(g)
    t2 = time.perf_counter(); tarjan(g)
    t3 = time.perf_counter()
    print(f"{m:9d}  {1000 * (t1 - t0):9.1f}  {1000 * (t2 - t1):9.1f}  {1000 * (t3 - t2):11.1f}  {1e6 * (t3 - t2) / m:23.2f}")

In 32-bit Pyodide, with smaller pointers and objects, lists occupy 4.92 MB and CSR 0.88 MB, ratio 5.6. On 64-bit CPython, measured outside the browser on the same graph, lists occupied 9.04 MB and the ratio was 10.3, the order of the memory figure’s model. In scaling, Tarjan cost per edge stays around 0.4 µs as edge count grows eightfold (with variation from coarse timing and cache): the proved Θ(n+m)\Theta(n + m).

With libraries

For large static graphs none of this needs to be written from scratch. scipy.sparse.csgraph operates on CSR matrices (the same format as above): connected_components(M, directed=True, connection="strong") returns strongly connected components, breadth_first_order and depth_first_order give traversals, all in C. It lacks topological sorting: networkx handles that (topological_sort, topological_generations for waves, condensation, strongly_connected_components, bridges, articulation_points), at the cost of being much slower with dictionaries of dictionaries.

The lab applies the same operations used on toy graphs to a real one: the import graph of a Python package. Read modules of networkx, parse each file with ast and store edge d→md \to m when mm imports dd at module level (the edge means, as in the figure, “dd must be ready before mm”).

[ ]The import graph of a real packageBrowser
import ast
import importlib
import importlib.util
import pkgutil


def listar_modulos(paquete):
    """Todos los módulos y subpaquetes de un paquete instalado: nombre -> es_paquete."""
    raiz = importlib.import_module(paquete)
    info = {paquete: True}
    for m in pkgutil.walk_packages(raiz.__path__, paquete + "."):
        info[m.name] = m.ispkg
    return info


def fuente(nombre):
    return importlib.util.find_spec(nombre).loader.get_source(nombre) or ""


def importados(nombre, es_paquete, conocidos):
    """Módulos del propio paquete que `nombre` importa a nivel de módulo (sin mirar dentro de funciones)."""
    base = nombre if es_paquete else nombre.rpartition(".")[0]
    pila, destinos = list(ast.parse(fuente(nombre)).body), set()
    while pila:
        nodo = pila.pop()
        if isinstance(nodo, (ast.FunctionDef, ast.AsyncFunctionDef)):
            continue
        if isinstance(nodo, ast.Import):
            for a in nodo.names:
                partes = a.name.split(".")
                for i in range(1, len(partes) + 1):       # importar a.b.c ejecuta también a y a.b
                    destinos.add(".".join(partes[:i]))
        elif isinstance(nodo, ast.ImportFrom):
            origen = nodo.module or ""
            if nodo.level:                                 # import relativo
                subir = base.split(".")[: len(base.split(".")) - (nodo.level - 1)]
                origen = ".".join(subir + ([origen] if origen else []))
            partes = origen.split(".")
            for i in range(1, len(partes) + 1):
                destinos.add(".".join(partes[:i]))
            for a in nodo.names:                           # from p import m puede importar el módulo p.m
                destinos.add(origen + "." + a.name)
        pila.extend(ast.iter_child_nodes(nodo))
    destinos.discard(nombre)
    return destinos & conocidos


t0 = time.perf_counter()
info = listar_modulos("networkx")
nombres = sorted(m for m in info if ".tests" not in m)          # sin los módulos de pruebas
indice = {m: i for i, m in enumerate(nombres)}
conocidos = set(nombres)
pares = sorted({(indice[d], indice[m]) for m in nombres for d in importados(m, info[m], conocidos)})
t1 = time.perf_counter()
print(f"{len(nombres)} módulos, {len(pares)} aristas de importación (leído y analizado en {t1 - t0:.1f} s)")

Second practice cell: components and ordering with all three implementations, with a surprise about the graph itself.

[ ]Components and order: custom implementation, scipy and networkxBrowser
from scipy.sparse.csgraph import breadth_first_order, depth_first_order

n_mod = len(nombres)
g = CSR(n_mod, pares)
M = csr_matrix((np.ones(len(pares), dtype=np.int8), ([a for a, _ in pares], [b for _, b in pares])), shape=(n_mod, n_mod))
print("el CSR de scipy tiene los mismos indptr e indices (como conjuntos por fila):",
      list(M.indptr) == g.indptr and all(set(M.indices[M.indptr[u]:M.indptr[u + 1]]) == set(g.vecinos(u)) for u in range(n_mod)))

t0 = time.perf_counter(); comp, nc = tarjan(g)
t1 = time.perf_counter(); nc_s, lab_s = connected_components(M, directed=True, connection="strong")
t2 = time.perf_counter(); G = nx.DiGraph(pares); nc_x = len(list(nx.strongly_connected_components(G)))
t3 = time.perf_counter()
tam = np.bincount(comp)
print(f"componentes fuertemente conexas: Tarjan {nc}, scipy {nc_s}, networkx {nc_x}; mayor componente: {tam.max()} módulos")
print(f"tiempos: propio {1000 * (t1 - t0):.2f} ms, scipy {1000 * (t2 - t1):.2f} ms, networkx (con construir el grafo) {1000 * (t3 - t2):.2f} ms")

# la sorpresa: un ciclo gigante que viene del mecanismo de los paquetes. Quitando las aristas hacia paquetes ascendientes
# (el «import networkx as nx» de un submódulo, que solo se usa en tiempo de ejecución), el grafo se queda sin ciclos.
def es_ascendiente(a, b):
    return nombres[b].startswith(nombres[a] + ".")

sin_asc = [(a, b) for a, b in pares if not es_ascendiente(a, b)]
g2 = CSR(n_mod, sin_asc)
orden, _ = kahn(g2)
print(f"sin aristas hacia ascendientes: {len(sin_asc)} aristas, Kahn coloca {len(orden)} de {n_mod} módulos")
G2 = nx.DiGraph(sin_asc)
G2.add_nodes_from(range(n_mod))
olas = list(nx.topological_generations(G2))
print(f"orden válido: {verificar_orden(g2, orden)}; olas de compilación (camino crítico + 1): {len(olas)}, la más ancha tiene {max(map(len, olas))} módulos")
print("primeros módulos del orden:", [nombres[v] for v in orden[:4]])

# recorridos de scipy contra los propios
alc_scipy = set(breadth_first_order(M, 0, directed=True, return_predecessors=False))
alc_mio = {v for v, dv in enumerate(bfs(g, 0)) if dv >= 0}
alc_dfs = set(depth_first_order(M, 0, directed=True, return_predecessors=False))
print("alcanzables desde el paquete raíz: BFS de scipy == BFS propia:", alc_scipy == alc_mio, "; DFS de scipy == BFS propia:", alc_dfs == alc_mio, f"({len(alc_mio)} módulos)")

Three lessons from practice. First, scipy’s CSR is the one built by hand: indptr and indices are the same arrays (rows possibly in a different order), so csgraph routines can consume what was implemented here. Second, Python package structure itself creates a giant cycle: in the version of networkx loaded by Pyodide, 277 of 287 modules lie in one strongly connected component. This is because import networkx as nx inside a submodule is an edge to the root package, and the package’s __init__ imports every submodule. It is a “harmless” cycle (import is used at execution, not load time), and removing edges to ancestor packages makes the graph acyclic with a ten-wave compilation order, the widest containing 118 modules that could run in parallel. Third, timing: in this run scipy is the fastest implementation and networkx the slowest (also including graph construction), though with only a few hundred vertices all take milliseconds or less and the difference matters for millions of edges, not here.

Common mistakes

Exercises

ProofAcyclic if and only if no back edges
Prove: A directed graph is acyclic if and only if no depth-first search produces a back edge.
0
Use the white-path theorem: vv is a descendant of uu if and only if at time d[u]d[u] there is a path of white vertices from uu to vv. A loop v→vv \to v counts as a back edge and a cycle of length 1.

Step 1 of 4. (⇒\Rightarrow, by contrapositive) Suppose there is a back edge (u,v)(u, v). How do you obtain a cycle?

ProofThe greatest f lies in a source component
Prove: In any DFS of a directed graph GG, the strongly connected component of vertex xx with greatest finish time f[x]f[x] is a source of the condensation graph (no edge enters from another component). Use the lemma: if an edge goes from CC to C′C' with C≠C′C \ne C', then f(C)>f(C′)f(C) > f(C'), where f(C)=max⁡v∈Cf[v]f(C) = \max_{v \in C} f[v].
0
Let C=C(x)C = C(x) be xx's component, so f(C)=f[x]=max⁡vf[v]f(C) = f[x] = \max_v f[v].

Step 1 of 4. Reasoning by contradiction, what do you assume?

CodeIterative Tarjan
Implement componentes(n, aristas): receive a vertex count and directed edges (u, v) (loops and repeated edges are allowed) and return a list comp of length n with each vertex's strongly connected component number. Numbering must be reverse topological: every edge u -> v must satisfy comp[u] >= comp[v], and components must use numbers 0, 1, 2, ... without gaps. It must be iterative: tests include a path and a ring of 100000 vertices that would overflow Python recursion.
def componentes(n, aristas):
  """comp[v] = número de la componente fuertemente conexa de v, con comp[u] >= comp[v] para toda arista u -> v."""
  return []   # tu código
Shift+Enter to run
CodeTopological order with cycle certificate
Implement ordenar(n, aristas): return ('orden', lista) with a topological order of the n vertices if the directed graph is acyclic, or ('ciclo', lista) with a cycle otherwise. A cycle is a vertex list [v0, v1, ..., vk] with edges v0 -> v1, v1 -> v2, ..., vk -> v0 (a loop v -> v is cycle [v]). It must be iterative: tests include a path of 100000 vertices.
def ordenar(n, aristas):
  """('orden', lista) si el grafo es acíclico; ('ciclo', lista) con un ciclo si no."""
  return ("orden", [])   # tu código
Shift+Enter to run
QuizClassify DFS edges
Run DFS on the directed graph with vertices a,b,c,d,e,fa, b, c, d, e, f and edges a→ba \to b, a→ca \to c, a→da \to d, b→db \to d, c→bc \to b, c→ec \to e, d→ad \to a, e→de \to d, e→fe \to f, f→af \to a. Search starts at aa and visits each vertex's neighbors alphabetically; resulting times are a[1,12]a[1,12], b[2,5]b[2,5], d[3,4]d[3,4], c[6,11]c[6,11], e[7,10]e[7,10], f[8,9]f[8,9]. Which statements are true?

More than one answer may be correct.

QuizEdges in an undirected graph
In DFS of an undirected graph (each edge classified when first examined), which edge types can appear?
QuizIs preorder topological?
A colleague proposes ordering a DAG by increasing discovery time d[v]d[v] of a DFS and claims it is topological. What does a reviewer say?
QuizWhich algorithm for which problem?
Which problem–tool pairings are correct?

More than one answer may be correct.

NumericA large graph in CSR
A graph with n=107n = 10^7 vertices and m=108m = 10^8 directed edges is stored in CSR using 32-bit indices (4 bytes per integer): an indptr array of n+1n + 1 integers and an indices array of mm integers. How many bytes total?
NumericThe same graph in Python lists
For the same graph (n=107n = 10^7, m=108m = 10^8) in a Python list of lists, use the lesson's model: each vertex costs 8 bytes (its pointer in the outer list) plus 56 bytes (its list header), and each edge costs 8 bytes (list pointer) plus 28 bytes (the int object, distinct per edge). How many times as much memory does it use as the previous exercise's 32-bit CSR? Answer to two decimals.
NumericCount topological orders
The DAG has vertices 1,…,71, \dots, 7 and edges 1→41 \to 4, 2→42 \to 4, 3→53 \to 5, 4→64 \to 6, 5→65 \to 6, 6→76 \to 7. How many distinct topological orders does it have?
NumericArticulation points
An undirected graph has 11 vertices and edges {1,2},{2,3},{3,1},{3,4},{4,5},{5,6},{6,4},{6,7},{7,8},{8,9},{9,7},{1,10},{10,11}\{1,2\}, \{2,3\}, \{3,1\}, \{3,4\}, \{4,5\}, \{5,6\}, \{6,4\}, \{6,7\}, \{7,8\}, \{8,9\}, \{9,7\}, \{1,10\}, \{10,11\}. How many articulation points does it have?

Summary

Key idea
Depth-first search records when each vertex opens and closes, and these intervals, nested like parentheses, suffice to classify edges, topologically order, split a directed graph into strong components and find bridges, all in Θ(n+m)\Theta(n + m).
  • Representation. Matrix Θ(n2)\Theta(n^2), lists Θ(n+m)\Theta(n + m), CSR Θ(n+m)\Theta(n + m) compact and static; choose by density and operations. Build CSR by counting sort; it is the format of scipy.sparse.
  • BFS with deque gives edge distances in Θ(n+m)\Theta(n + m); with list.pop(0) it becomes quadratic.
  • DFS. Times dd and ff; parenthesis theorem (disjoint or nested intervals) and white-path theorem; tree, back, forward and cross edges by destination color; undirected graphs have only tree and back edges.
  • Topological order. Exists iff the graph is acyclic. Kahn (in-degrees, waves, cycle certificate from remaining vertices) and DFS (decreasing ff; a back edge gives a cycle). Both return verifiable certificates.
  • Strong components. The condensation is a DAG. Kosaraju: two DFS traversals and the transpose, with the lemma that inter-component edges decrease in ff. Tarjan: one pass with stack and low\mathrm{low}; a component closes when low=idx\mathrm{low} = \mathrm{idx}, numbered in reverse topological order. Applications: 2-SAT, mutual recursion, dependency analysis.
  • Bridges and articulation points. (p,c)(p, c) is a bridge iff low(c)>d[p]\mathrm{low}(c) > d[p]; a vertex is an articulation point if a child satisfies low(c)≥d[v]\mathrm{low}(c) \ge d[v], or it is a root with two children. Always use iteration and skip the arrival edge by ID.

These traversals underpin what follows. Shortest paths in a DAG from the shortest-path lesson are dynamic programming in topological order (the same structure as subproblems as a DAG), and Dijkstra and maximum-flow algorithms reuse BFS and DFS with other data structures. In Datalog with stratified negation rule evaluation follows a topological order of dependency-graph components, and backpropagation engines traverse the computation graph in reverse topological order.